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

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

Introduction

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

Prototype

@Override
    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
            throws BeanDefinitionStoreException 

Source Link

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.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 ww . j  a v a2s . c om
 *
 * @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:nz.co.senanque.madura.bundle.BundleRootImpl.java

public void init(DefaultListableBeanFactory ownerBeanFactory, Properties properties, ClassLoader cl,
        Map<String, Object> inheritableBeans) {
    m_properties = properties;//  w w w.  ja  va 2s .c  o m
    m_inheritableBeans = inheritableBeans;
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(cl);
    m_classLoader = cl;
    GenericApplicationContext ctx = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
    String contextPath = properties.getProperty("Bundle-Context", "/bundle-spring.xml");
    m_logger.debug("loading context: {}", contextPath);
    ClassPathResource classPathResource = new ClassPathResource(contextPath, cl);
    xmlReader.loadBeanDefinitions(classPathResource);
    PropertyPlaceholderConfigurer p = new PropertyPlaceholderConfigurer();
    p.setProperties(properties);
    ctx.addBeanFactoryPostProcessor(p);
    if (m_logger.isDebugEnabled()) {
        dumpClassLoader(cl);
    }
    for (Map.Entry<String, Object> entry : inheritableBeans.entrySet()) {
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder
                .genericBeanDefinition(InnerBundleFactory.class);
        beanDefinitionBuilder.addPropertyValue("key", entry.getKey());
        beanDefinitionBuilder.addPropertyValue("object", inheritableBeans.get(entry.getKey()));
        ctx.registerBeanDefinition(entry.getKey(), beanDefinitionBuilder.getBeanDefinition());
    }
    Scope scope = ownerBeanFactory.getRegisteredScope("session");
    if (scope != null) {
        ctx.getBeanFactory().registerScope("session", scope);
    }
    ctx.refresh();
    m_applicationContext = ctx;
    Thread.currentThread().setContextClassLoader(classLoader);
}

From source file:org.apache.camel.spring.javaconfig.test.JavaConfigContextLoader.java

/**
 * Loads a new {@link ApplicationContext context} based on the supplied {@code locations},
 * configures the context, and finally returns the context in fully <em>refreshed</em> state.
 * <p/>//ww  w  .j  a  v  a  2 s.c  om
 *
 * Configuration locations are either fully-qualified class names or base package names. These
 * locations will be given to a {@link JavaConfigApplicationContext} for configuration via the
 * {@link JavaConfigApplicationContext#addConfigClass(Class)} and
 * {@link JavaConfigApplicationContext#addBasePackage(String)} methods.
 *
 * @param locations the locations to use to load the application context
 * @return a new application context
 * @throws IllegalArgumentException if any of <var>locations</var> are not valid fully-qualified
 * Class or Package names
 */
public ApplicationContext loadContext(String... locations) {
    if (logger.isDebugEnabled()) {
        logger.debug("Creating a JavaConfigApplicationContext for " + Arrays.asList(locations));
    }

    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

    ArrayList<Class<?>> configClasses = new ArrayList<Class<?>>();
    ArrayList<String> basePackages = new ArrayList<String>();
    for (String location : locations) {
        // if the location refers to a class, use it. Otherwise assume it's a base package name
        try {
            final Class<?> aClass = this.getClass().getClassLoader().loadClass(location);
            configClasses.add(aClass);
        } catch (ClassNotFoundException e) {
            if (Package.getPackage(location) == null) {
                throw new IllegalArgumentException(
                        String.format("A non-existent class or package name was specified: [%s]", location));
            }
            basePackages.add(location);
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Setting config classes to " + configClasses);
        logger.debug("Setting base packages to " + basePackages);
    }

    for (Class<?> configClass : configClasses) {
        context.register(configClass);
    }

    for (String basePackage : basePackages) {
        context.scan(basePackage);
    }

    context.refresh();

    // Have to create a child context that implements BeanDefinitionRegistry
    // to pass to registerAnnotationConfigProcessors, since
    // JavaConfigApplicationContext does not
    final GenericApplicationContext gac = new GenericApplicationContext(context);
    AnnotationConfigUtils.registerAnnotationConfigProcessors(gac);
    // copy BeanPostProcessors to the child context
    for (String bppName : context.getBeanFactory().getBeanNamesForType(BeanPostProcessor.class)) {
        gac.registerBeanDefinition(bppName, context.getBeanFactory().getBeanDefinition(bppName));
    }
    gac.refresh();
    gac.registerShutdownHook();

    return gac;
}

From source file:org.openadaptor.spring.SpringAdaptor.java

/**
 * Configure the default PropertyPlaceholderConfigurer.
 * <br>//from  w w  w.  ja v a  2s  .co  m
 * Unless suppressAutomaticPropsConfig is set true by supplying -noprops as a command line arg then
 * this method creates and installs a PropertyPlaceholderConfigurer which allows access to System Properties
 * and optionally add all -props defined urls as property resource locations.<br>
 * With one exception all urls are passed through to the context in order to locate the resource. The exception
 * is a url that is not prefixed with a protocol is assumed to be a file and arbitratily prefixed with "file:"<br>
 * NB the arbitrary name given to the generated PropertyPlaceholderConfigurer is "openadaptorAutoGeneratedSystemPropertyConfigurer".
 *
 * @param context Spring Context being used.
 * @param propsUrlList Supplied List or Property URLS.
 */
protected void configureProperties(GenericApplicationContext context, ArrayList propsUrlList) {
    // System properties

    if (!suppressAutomaticPropsConfig) {

        if (isPropertyPlaceholderPresent(context)) {
            log.warn(
                    "Spring configuration file already has PropertyPlaceholderConfigurers defined. Please ensure any conflicts are resolved satisfactorily.");
        }

        MutablePropertyValues systemPropertiesModeProperties = new MutablePropertyValues();
        systemPropertiesModeProperties.addPropertyValue("staticField",
                "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_FALLBACK");

        RootBeanDefinition systemPropertiesMode = new RootBeanDefinition(FieldRetrievingFactoryBean.class);
        systemPropertiesMode.setPropertyValues(systemPropertiesModeProperties);

        MutablePropertyValues properties = new MutablePropertyValues();
        properties.addPropertyValue("ignoreResourceNotFound", "false"); // Will cause an eror if a resource url is bogus
        Iterator propsUrlIter = propsUrlList.iterator();
        ArrayList resourceList = new ArrayList();
        while (propsUrlIter.hasNext()) {
            resourceList.add(context.getResource(ensureProtocol((String) propsUrlIter.next())));
        }
        properties.addPropertyValue("locations", resourceList);
        properties.addPropertyValue("systemPropertiesMode", systemPropertiesMode);
        RootBeanDefinition propertyHolder = new RootBeanDefinition(PropertyPlaceholderConfigurer.class);
        propertyHolder.setPropertyValues(properties);

        context.registerBeanDefinition("openadaptorAutoGeneratedSystemPropertyConfigurer", propertyHolder);
    }
}

From source file:org.opentripplanner.integration.benchmark.RunBenchmarkPlanMain.java

private GenericApplicationContext getApplicationContext() {

    GenericApplicationContext ctx = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
    xmlReader.loadBeanDefinitions(new ClassPathResource("org/opentripplanner/application-context.xml"));

    Map<String, BeanDefinition> additionalBeans = getAdditionalBeans();
    for (Map.Entry<String, BeanDefinition> entry : additionalBeans.entrySet())
        ctx.registerBeanDefinition(entry.getKey(), entry.getValue());

    ctx.refresh();//w w w .  ja  v  a  2s.c  o  m
    ctx.registerShutdownHook();
    return ctx;
}

From source file:org.pentaho.platform.plugin.services.pluginmgr.DefaultPluginManager.java

/**
 * Initializes a bean factory for serving up instance of plugin classes.
 *
 * @return an instance of the factory that allows callers to continue to define more beans on it programmatically
 *//*from w  ww .  jav  a2 s.  c o m*/
protected void initializeBeanFactory(final IPlatformPlugin plugin, final ClassLoader loader)
        throws PlatformPluginRegistrationException {

    if (!(loader instanceof PluginClassLoader)) {
        logger.warn(
                "Can't determine plugin dir to load spring file because classloader is not of type PluginClassLoader.  "
                        //$NON-NLS-1$
                        + "This is since we are probably in a unit test"); //$NON-NLS-1$
        return;
    }

    //
    // Get the native factory (the factory that comes preconfigured via either Spring bean files or via JUnit test
    //
    BeanFactory nativeBeanFactory = getNativeBeanFactory(plugin, loader);

    //
    // Now create the definable factory for accepting old style bean definitions from IPluginProvider
    //

    GenericApplicationContext beanFactory = null;
    if (nativeBeanFactory != null && nativeBeanFactory instanceof GenericApplicationContext) {
        beanFactory = (GenericApplicationContext) nativeBeanFactory;
    } else {
        beanFactory = new GenericApplicationContext();
        beanFactory.setClassLoader(loader);
        beanFactory.getBeanFactory().setBeanClassLoader(loader);

        if (nativeBeanFactory != null) {
            beanFactory.getBeanFactory().setParentBeanFactory(nativeBeanFactory);
        }
    }

    beanFactoryMap.put(plugin.getId(), beanFactory);

    //
    // Register any beans defined via the pluginProvider
    //

    // we do not have to synchronize on the bean set here because the
    // map that backs the set is never modified after the plugin has
    // been made available to the plugin manager
    for (PluginBeanDefinition def : plugin.getBeans()) {
        // register by classname if id is null
        def.setBeanId((def.getBeanId() == null) ? def.getClassname() : def.getBeanId());
        assertUnique(plugin.getId(), def.getBeanId());
        // defining plugin beans the old way through the plugin provider ifc supports only prototype scope
        BeanDefinition beanDef = BeanDefinitionBuilder.rootBeanDefinition(def.getClassname())
                .setScope(BeanDefinition.SCOPE_PROTOTYPE).getBeanDefinition();
        beanFactory.registerBeanDefinition(def.getBeanId(), beanDef);
    }

    StandaloneSpringPentahoObjectFactory pentahoFactory = new StandaloneSpringPentahoObjectFactory(
            "Plugin Factory ( " + plugin.getId() + " )");
    pentahoFactory.init(null, beanFactory);

}

From source file:org.pentaho.platform.plugin.services.pluginmgr.DefaultPluginManager.java

private void registerContentGenerators(IPlatformPlugin plugin, ClassLoader loader)
        throws PlatformPluginRegistrationException {
    // register the content generators
    for (IContentGeneratorInfo cgInfo : plugin.getContentGenerators()) {
        // define the bean in the factory
        BeanDefinition beanDef = BeanDefinitionBuilder.rootBeanDefinition(cgInfo.getClassname())
                .setScope(BeanDefinition.SCOPE_PROTOTYPE).getBeanDefinition();
        GenericApplicationContext factory = beanFactoryMap.get(plugin.getId());
        // register bean with alias of content generator id (old way)
        factory.registerBeanDefinition(cgInfo.getId(), beanDef);
        // register bean with alias of type (with default perspective) as well (new way)
        factory.registerAlias(cgInfo.getId(), cgInfo.getType());

        PluginMessageLogger.add(Messages.getInstance()
                .getString("PluginManager.USER_CONTENT_GENERATOR_REGISTERED", cgInfo.getId(), plugin.getId())); //$NON-NLS-1$
    }//from  w ww .  ja  v a  2  s. c o  m
}

From source file:org.springframework.aop.aspectj.autoproxy.AspectJAutoProxyCreatorTests.java

@Test
public void testAspectsAndAdvisorNotAppliedToManySingletonsIsFastEnough() {
    Assume.group(TestGroup.PERFORMANCE);
    Assume.notLogging(factoryLog);//from   www . j ava  2  s  .c om
    GenericApplicationContext ac = new GenericApplicationContext();
    new XmlBeanDefinitionReader(ac)
            .loadBeanDefinitions(new ClassPathResource(qName("aspectsPlusAdvisor.xml"), getClass()));
    for (int i = 0; i < 10000; i++) {
        ac.registerBeanDefinition("singleton" + i, new RootBeanDefinition(NestedTestBean.class));
    }
    StopWatch sw = new StopWatch();
    sw.start("Singleton Creation");
    ac.refresh();
    sw.stop();

    // What's a reasonable expectation for _any_ server or developer machine load?
    // 8 seconds?
    assertStopWatchTimeLimit(sw, 8000);
}

From source file:org.springframework.aop.aspectj.autoproxy.AspectJAutoProxyCreatorTests.java

@Test
public void testAspectsAndAdvisorAreAppliedEvenIfComingFromParentFactory() {
    ClassPathXmlApplicationContext ac = newContext("aspectsPlusAdvisor.xml");
    GenericApplicationContext childAc = new GenericApplicationContext(ac);
    // Create a child factory with a bean that should be woven
    RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
    bd.getPropertyValues().addPropertyValue(new PropertyValue("name", "Adrian"))
            .addPropertyValue(new PropertyValue("age", new Integer(34)));
    childAc.registerBeanDefinition("adrian2", bd);
    // Register the advisor auto proxy creator with subclass
    childAc.registerBeanDefinition(AnnotationAwareAspectJAutoProxyCreator.class.getName(),
            new RootBeanDefinition(AnnotationAwareAspectJAutoProxyCreator.class));
    childAc.refresh();//from www .  j  a  v a 2s .  c o  m

    ITestBean beanFromChildContextThatShouldBeWeaved = (ITestBean) childAc.getBean("adrian2");
    //testAspectsAndAdvisorAreApplied(childAc, (ITestBean) ac.getBean("adrian"));
    doTestAspectsAndAdvisorAreApplied(childAc, beanFromChildContextThatShouldBeWeaved);
}