Example usage for org.springframework.context.support GenericApplicationContext GenericApplicationContext

List of usage examples for org.springframework.context.support GenericApplicationContext GenericApplicationContext

Introduction

In this page you can find the example usage for org.springframework.context.support GenericApplicationContext GenericApplicationContext.

Prototype

public GenericApplicationContext() 

Source Link

Document

Create a new GenericApplicationContext.

Usage

From source file:org.mybatis.spring.config.NamespaceTest.java

private GenericApplicationContext setupSqlSessionFactory() {

    GenericApplicationContext genericApplicationContext = new GenericApplicationContext();

    GenericBeanDefinition definition = new GenericBeanDefinition();
    definition.setBeanClass(SqlSessionFactoryBean.class);
    definition.getPropertyValues().add("dataSource", new MockDataSource());

    DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
    factory.registerBeanDefinition("sqlSessionFactory", definition);

    genericApplicationContext.registerBeanDefinition("sqlSessionFactory", definition);

    genericApplicationContext.refresh();

    return genericApplicationContext;
}

From source file:com.acc.xstream.XmlXStreamMarshallerFactoryTest.java

@Test
public void testInstantiateBeanFactory() {

    final GenericApplicationContext applicationContext = new GenericApplicationContext();
    final XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(applicationContext);
    xmlReader.loadBeanDefinitions(new ByteArrayResource(SERVICE_BEAN_DEF.getBytes()));
    applicationContext.refresh();/*w w w  .j av a 2s.c  o m*/

    final XStreamMarshaller instanceOneXStream = (XStreamMarshaller) applicationContext
            .getBean("onlyOneInstance");
    final XStreamMarshaller instanceTwoXStream = (XStreamMarshaller) applicationContext
            .getBean("onlyOneInstance");

    Assert.assertSame("Factory should produce same instance ", instanceOneXStream, instanceTwoXStream);

}

From source file:com.brienwheeler.lib.spring.beans.PropertyPlaceholderConfigurer.java

/**
 * Programatically process a single property file location, using System
 * properties in preference to included definitions for placeholder
 * resolution, and setting any resolved properties as System properties, if
 * no property by that name already exists.
 * /*from   w ww  .ja va 2  s  .  c o  m*/
 * @param locationName String-encoded resource location for the properties file to process
 * @param placeholderPrefix the placeholder prefix String
 * @param placeholderSuffix the placeholder suffix String
 */
public static void processLocation(String locationName, String placeholderPrefix, String placeholderSuffix) {
    ResourceEditor resourceEditor = new ResourceEditor();
    resourceEditor.setAsText(locationName);

    PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
    configurer.setLocation((Resource) resourceEditor.getValue());
    if (placeholderPrefix != null)
        configurer.setPlaceholderPrefix(placeholderPrefix);
    if (placeholderSuffix != null)
        configurer.setPlaceholderSuffix(placeholderSuffix);
    configurer.quiet = true;

    GenericApplicationContext context = new GenericApplicationContext();
    context.getBeanFactory().registerSingleton("propertyPlaceholderConfigurer", configurer);
    context.refresh();
    context.close();
}

From source file:com.sitewhere.server.SiteWhereServer.java

/**
 * Load the springified server configuration.
 * //from w  ww  .j av a  2 s.co  m
 * @return
 */
protected ApplicationContext loadServerApplicationContext(File configFile) throws SiteWhereException {
    GenericApplicationContext context = new GenericApplicationContext();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
    reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
    reader.loadBeanDefinitions(new FileSystemResource(configFile));
    context.refresh();
    return context;
}

From source file:it.scoppelletti.programmerpower.console.spring.ConsoleApplicationRunner.java

/**
 * Inizializza il contesto dell’applicazione.
 * //from  w w w . j  av a2 s .  co  m
 * @param  ui Interfaccia utente.
 * @return    Oggetto.
 */
private GenericApplicationContext initApplicationContext(UserInterfaceProvider ui) {
    SingletonBeanRegistry beanRegistry;
    GenericApplicationContext ctx = null;
    GenericApplicationContext applCtx;
    XmlBeanDefinitionReader reader;
    ConfigurableEnvironment env;
    PropertySource<?> propSource;
    MutablePropertySources propSources;

    try {
        ctx = new GenericApplicationContext();
        reader = new XmlBeanDefinitionReader(ctx);
        reader.loadBeanDefinitions(ConsoleApplicationRunner.CONSOLE_CONTEXT);
        reader.loadBeanDefinitions(initApplicationContextResourceName());

        beanRegistry = ctx.getBeanFactory();
        beanRegistry.registerSingleton(ConsoleApplicationRunner.BEAN_NAME, this);
        beanRegistry.registerSingleton(UserInterfaceProvider.BEAN_NAME, ui);

        env = ctx.getEnvironment();

        // Acquisisco gli eventuali profili configurati prima di aggiungere
        // quello di Programmer Power
        env.getActiveProfiles();

        env.addActiveProfile(ConsoleApplicationRunner.PROFILE);

        propSources = env.getPropertySources();

        propSources.addFirst(new ConsolePropertySource(ConsolePropertySource.class.getName(), this));

        propSource = BeanConfigUtils.loadPropertySource();
        if (propSource != null) {
            propSources.addFirst(propSource);
        }

        ctx.refresh();
        applCtx = ctx;
        ctx = null;
    } finally {
        if (ctx != null) {
            ctx.close();
            ctx = null;
        }
    }

    return applCtx;
}

From source file:com.google.code.guice.repository.configuration.JpaRepositoryModule.java

/**
 * Creates Spring application context based on found persistence units. Context will be initialized with multiple
 * persistence units support.//w  w  w .  ja v a2  s. co  m
 *
 * @param configurationManager configuration manager with persistence units configurations.
 *
 * @return initialized Spring context
 *
 * @see <a href="https://github.com/SpringSource/spring-data-jpa/blob/master/src/test/resources/multiple-entity-manager-integration-context.xml"/>
 */
protected ApplicationContext createApplicationContext(
        PersistenceUnitsConfigurationManager configurationManager) {
    GenericApplicationContext context = new GenericApplicationContext();

    String abstractEMFBeanName = "abstractEntityManagerFactory";
    context.registerBeanDefinition(abstractEMFBeanName,
            BeanDefinitionBuilder.genericBeanDefinition(LocalContainerEntityManagerFactoryBean.class)
                    .setAbstract(true).getBeanDefinition());

    Iterable<PersistenceUnitConfiguration> configurations = configurationManager.getConfigurations();
    for (PersistenceUnitConfiguration configuration : configurations) {
        String persistenceUnitName = configuration.getPersistenceUnitName();
        logger.info(String.format("Processing persistence unit: [%s]", persistenceUnitName));
        Map props = configuration.getProperties();

        String entityManagerFactoryName = "entityManagerFactory#" + persistenceUnitName;

        BeanDefinitionBuilder emfFactoryDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition()
                .setParentName(abstractEMFBeanName).addPropertyValue("persistenceUnitName", persistenceUnitName)
                .addPropertyValue("jpaProperties", props);

        // Additional EntityManagerFactory properties for Spring EMFBean initialization - s.a. jpaDialect, jpaVendorAdapter
        Map<String, Object> properties = getAdditionalEMFProperties(persistenceUnitName);
        if (properties != null) {
            for (String propertyName : properties.keySet()) {
                Object value = properties.get(propertyName);
                if (value != null) {
                    logger.info(
                            String.format("Found additional EMF property: [%s] -> [%s]", propertyName, value));
                    emfFactoryDefinitionBuilder.addPropertyValue(propertyName, value);
                }
            }
        }

        context.registerBeanDefinition(entityManagerFactoryName,
                emfFactoryDefinitionBuilder.getBeanDefinition());

        // Naming is important - it's needed for later TransactionManager resolution based on @Transactional value with persistenceUnitName
        context.registerBeanDefinition(persistenceUnitName,
                BeanDefinitionBuilder.genericBeanDefinition(JpaTransactionManager.class)
                        .addPropertyReference("entityManagerFactory", entityManagerFactoryName)
                        .getBeanDefinition());

        PlatformTransactionManager transactionManager = context.getBean(persistenceUnitName,
                PlatformTransactionManager.class);
        TransactionInterceptor transactionInterceptor = new TransactionInterceptor(transactionManager,
                createTransactionAttributeSource());
        transactionInterceptor.setBeanFactory(context);

        // Wiring components
        EntityManagerFactory emf = context.getBean(entityManagerFactoryName, EntityManagerFactory.class);
        EntityManager entityManager = SharedEntityManagerCreator.createSharedEntityManager(emf, props);
        configuration.setEntityManager(entityManager);
        configuration.setEntityManagerFactory(emf);
        configuration.setTransactionManager(transactionManager);
        configuration.setTransactionManagerName(persistenceUnitName);
        configuration.setTransactionInterceptor(transactionInterceptor);

        // Default bindings for EMF & Transaction Manager - they needed for repositories with @Transactional without value
        if (configuration.isDefault()) {
            context.registerAlias(entityManagerFactoryName, "entityManagerFactory");
            context.registerAlias(persistenceUnitName, "transactionManager");
        }
    }

    return context;
}

From source file:com.github.yihtserns.logback.spring.config.LogbackNamespaceHandlerTest.java

private static GenericApplicationContext newApplicationContextFor(String xml) {
    GenericApplicationContext applicationContext = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(applicationContext);
    xmlReader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
    xmlReader.loadBeanDefinitions(new InputSource(new StringReader(xml)));

    applicationContext.refresh();/*  www.  j  ava2  s. c  om*/
    applicationContext.start();

    return applicationContext;
}

From source file:de.hybris.platform.btgcockpit.service.BTGCockpitServiceTest.java

public void initApplicationContext() {
    final GenericApplicationContext context = new GenericApplicationContext();
    context.setResourceLoader(new DefaultResourceLoader(Registry.class.getClassLoader()));
    context.setClassLoader(Registry.class.getClassLoader());
    context.getBeanFactory().setBeanClassLoader(Registry.class.getClassLoader());
    context.setParent(Registry.getGlobalApplicationContext());
    final XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(context);
    xmlReader.setDocumentReaderClass(ScopeTenantIgnoreDocReader.class);
    xmlReader.setBeanClassLoader(Registry.class.getClassLoader());
    xmlReader.loadBeanDefinitions(getSpringConfigurationLocations());
    context.refresh();/*from   w w w.  j ava2 s. c o m*/
    final AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory();
    beanFactory.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true);
    this.applicationContex = context;
}

From source file:no.abmu.finances.utils.FinanceImporter.java

protected ApplicationContext getApplicationContext() {
    if (applicationContext == null) {
        applicationContext = new GenericApplicationContext();
        XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(applicationContext);

        String[] configLocations = getConfigLocations();
        for (int i = 0; i < configLocations.length; i++) {
            String configLocation = configLocations[i];
            xmlReader.loadBeanDefinitions(new ClassPathResource(configLocation));
        }/*w w  w .  j a  v  a 2 s  .c  o m*/
        applicationContext.refresh();

    }
    return applicationContext;
}

From source file:no.abmu.organisationregister.util.OrgUnitImporter.java

public OrgUnitImporter(boolean doRollback) {
    applicationContext = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(applicationContext);
    xmlReader.loadBeanDefinitions(//from w  w  w .  java 2  s .  c o m
            new ClassPathResource("conf/common/spring/hibernate2/appContext-configuration.xml"));
    xmlReader.loadBeanDefinitions(
            new ClassPathResource("conf/common/spring/hibernate2/appContext-dataLayer-general.xml"));
    xmlReader.loadBeanDefinitions(
            new ClassPathResource("conf/common/spring/appContext-dataLayer-standalone.xml"));
    xmlReader.loadBeanDefinitions(new ClassPathResource(
            "conf/organisationregister/spring/hibernate2/appContext-service-orgRegister.xml"));
    xmlReader.loadBeanDefinitions(
            new ClassPathResource("conf/common/spring/hibernate2/appContext-util-postgres.xml"));

    xmlReader.loadBeanDefinitions(
            new ClassPathResource("conf/finances/spring/appContext-mappings-finances.xml"));
    xmlReader.loadBeanDefinitions(
            new ClassPathResource("conf/organisationregister/spring/appContext-mappings-orgreg.xml"));
    xmlReader.loadBeanDefinitions(new ClassPathResource("conf/user/spring/appContext-mappings-user.xml"));

    xmlReader.loadBeanDefinitions(new ClassPathResource("conf/common/spring/appContext-dummyAudit.xml"));

    applicationContext.refresh();

    this.doRollback = doRollback;
}