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:com.textocat.textokit.eval.EvaluationLauncher.java

public static void runUsingProperties(Properties configProperties) throws Exception {
    GenericApplicationContext appCtx = new GenericApplicationContext();

    appCtx.getEnvironment().getPropertySources()
            .addLast(new PropertiesPropertySource("configFile", configProperties));

    XmlBeanDefinitionReader xmlBDReader = new XmlBeanDefinitionReader(appCtx);
    xmlBDReader.loadBeanDefinitions(APP_CONTEXT_LOCATION);

    // register listeners
    Map<String, String> listenerImpls = getPrefixedKeyPairs(configProperties, PREFIX_LISTENER_ID);
    for (String listenerId : listenerImpls.keySet()) {
        String listenerClass = listenerImpls.get(listenerId);
        BeanDefinitionBuilder bb = genericBeanDefinition(listenerClass);
        Map<String, String> listenerProperties = getPrefixedKeyPairs(configProperties,
                PREFIX_LISTENER_PROPERTY + listenerId + ".");
        for (String propName : listenerProperties.keySet()) {
            bb.addPropertyValue(propName, listenerProperties.get(propName));
        }/* ww  w .  j a  va  2s  . c om*/
        appCtx.registerBeanDefinition(listenerId, bb.getBeanDefinition());
    }

    appCtx.refresh();

    appCtx.registerShutdownHook();

    GoldStandardBasedEvaluation eval = appCtx.getBean(GoldStandardBasedEvaluation.class);
    eval.run();
}

From source file:org.uimafit.spring.SpringContextResourceManagerTest.java

private ApplicationContext getApplicationContext() {
    final GenericApplicationContext ctx = new GenericApplicationContext();
    AnnotationConfigUtils.registerAnnotationConfigProcessors(ctx);
    ctx.registerBeanDefinition("springBean", BeanDefinitionBuilder.genericBeanDefinition(String.class)
            .addConstructorArgValue("BEAN").getBeanDefinition());
    ctx.refresh();/*  www  .  ja v  a  2 s  .c  om*/
    return ctx;
}

From source file:org.joinfaces.annotations.JsfCdiToSpringApplicationBeanFactoryPostProcessorIT.java

@Test
public void testViewScopedClass() {
    GenericApplicationContext acx = new GenericApplicationContext();
    AnnotationConfigUtils.registerAnnotationConfigProcessors(acx);

    acx.registerBeanDefinition("viewScopedClass",
            new AnnotatedGenericBeanDefinition(new StandardAnnotationMetadata(ViewScopedClass.class)));
    acx.registerBeanDefinition("scopedBeansConfiguration",
            new RootBeanDefinition(ScopedBeansConfiguration.class));
    acx.addBeanFactoryPostProcessor(new JsfCdiToSpringBeanFactoryPostProcessor());
    acx.refresh();/*  w w  w  .  ja  va2s . co m*/

    assertThat(acx.getBeanDefinition("viewScopedClass").getScope()).isEqualTo(JsfCdiToSpring.VIEW);
    assertThat(acx.getBeanDefinition("viewScopedBean").getScope()).isEqualTo(JsfCdiToSpring.VIEW);
}

From source file:org.joinfaces.annotations.JsfCdiToSpringApplicationBeanFactoryPostProcessorIT.java

@Test
public void testSessionScopedClass() {
    GenericApplicationContext acx = new GenericApplicationContext();
    AnnotationConfigUtils.registerAnnotationConfigProcessors(acx);

    acx.registerBeanDefinition("sessionScopedClass",
            new AnnotatedGenericBeanDefinition(new StandardAnnotationMetadata(SessionScopedClass.class)));
    acx.registerBeanDefinition("scopedBeansConfiguration",
            new RootBeanDefinition(ScopedBeansConfiguration.class));
    acx.addBeanFactoryPostProcessor(new JsfCdiToSpringBeanFactoryPostProcessor());
    acx.refresh();//from www .j  a  v a2 s  .c  o m

    assertThat(acx.getBeanDefinition("sessionScopedClass").getScope()).isEqualTo(JsfCdiToSpring.SESSION);
    assertThat(acx.getBeanDefinition("sessionScopedBean").getScope()).isEqualTo(JsfCdiToSpring.SESSION);
}

From source file:org.joinfaces.annotations.JsfCdiToSpringApplicationBeanFactoryPostProcessorIT.java

@Test
public void testNoScopedClass() {
    GenericApplicationContext acx = new GenericApplicationContext();
    AnnotationConfigUtils.registerAnnotationConfigProcessors(acx);

    acx.registerBeanDefinition("noScopedClass",
            new AnnotatedGenericBeanDefinition(new StandardAnnotationMetadata(NoScopedClass.class)));
    acx.registerBeanDefinition("scopedBeansConfiguration",
            new RootBeanDefinition(ScopedBeansConfiguration.class));
    acx.addBeanFactoryPostProcessor(new JsfCdiToSpringBeanFactoryPostProcessor());
    acx.refresh();/*  ww w.ja  v  a  2 s  .c o m*/

    assertThat(acx.getBeanDefinition("noScopedClass").getScope()).isEqualTo("");
    assertThat(acx.getBeanDefinition("noScopedBean").getScope()).isEqualTo("");

}

From source file:org.uimafit.spring.UimaFactoryInjectionTest.java

private ApplicationContext getApplicationContext() {
    final GenericApplicationContext ctx = new GenericApplicationContext();
    AnnotationConfigUtils.registerAnnotationConfigProcessors(ctx);
    ctx.registerBeanDefinition("otherBean", BeanDefinitionBuilder.genericBeanDefinition(String.class)
            .addConstructorArgValue("BEAN").getBeanDefinition());

    ctx.registerBeanDefinition("analysisEngineFactory",
            BeanDefinitionBuilder.genericBeanDefinition(AnalysisEngineFactory_impl.class).getBeanDefinition());
    ctx.registerBeanDefinition("casConsumerFactory",
            BeanDefinitionBuilder.genericBeanDefinition(CasConsumerFactory_impl.class).getBeanDefinition());
    ctx.registerBeanDefinition("casInitializerFactory",
            BeanDefinitionBuilder.genericBeanDefinition(CasInitializerFactory_impl.class).getBeanDefinition());
    ctx.registerBeanDefinition("collectionReaderFactory", BeanDefinitionBuilder
            .genericBeanDefinition(CollectionReaderFactory_impl.class).getBeanDefinition());
    ctx.registerBeanDefinition("customResourceFactory",
            BeanDefinitionBuilder.genericBeanDefinition(CustomResourceFactory_impl.class).getBeanDefinition());
    ctx.refresh();// www.  j  a  v a  2 s  .c  om
    return ctx;
}

From source file:atunit.spring.SpringContainer.java

protected void fillInMissingFieldBeans(Class<?> testClass, GenericApplicationContext ctx) throws Exception {
    for (Field field : testClass.getDeclaredFields()) {
        Bean beanAnno = field.getAnnotation(Bean.class);
        if (beanAnno == null)
            continue;
        String name = beanAnno.value();
        if (!name.equals("") && !ctx.containsBean(name)) {
            ctx.registerBeanDefinition(name, defineAutowireBean(field.getType()));
        } else if (ctx.getBeansOfType(field.getType()).isEmpty()) {
            BeanDefinitionReaderUtils.registerWithGeneratedName(defineAutowireBean(field.getType()), ctx);
        }/*w  ww . j a  v a 2s . c om*/
    }
}

From source file:co.paralleluniverse.common.spring.SpringContainerHelper.java

public static ConfigurableApplicationContext createContext(String defaultDomain, Resource xmlResource,
        Object properties, BeanFactoryPostProcessor beanFactoryPostProcessor) {
    LOG.info("JAVA: {} {}, {}", new Object[] { System.getProperty("java.runtime.name"),
            System.getProperty("java.runtime.version"), System.getProperty("java.vendor") });
    LOG.info("OS: {} {}, {}", new Object[] { System.getProperty("os.name"), System.getProperty("os.version"),
            System.getProperty("os.arch") });
    LOG.info("DIR: {}", System.getProperty("user.dir"));

    final DefaultListableBeanFactory beanFactory = createBeanFactory();
    final GenericApplicationContext context = new GenericApplicationContext(beanFactory);
    context.registerShutdownHook();/*from   w w w.  j a v a2s  .c o m*/

    final PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
    propertyPlaceholderConfigurer
            .setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);

    if (properties != null) {
        if (properties instanceof Resource)
            propertyPlaceholderConfigurer.setLocation((Resource) properties);
        else if (properties instanceof Properties)
            propertyPlaceholderConfigurer.setProperties((Properties) properties);
        else
            throw new IllegalArgumentException(
                    "Properties argument - " + properties + " - is of an unhandled type");
    }
    context.addBeanFactoryPostProcessor(propertyPlaceholderConfigurer);

    // MBean exporter
    //final MBeanExporter mbeanExporter = new AnnotationMBeanExporter();
    //mbeanExporter.setServer(ManagementFactory.getPlatformMBeanServer());
    //beanFactory.registerSingleton("mbeanExporter", mbeanExporter);
    context.registerBeanDefinition("mbeanExporter", getMBeanExporterBeanDefinition(defaultDomain));

    // inject bean names into components
    context.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            for (String beanName : beanFactory.getBeanDefinitionNames()) {
                try {
                    final BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
                    if (beanDefinition.getBeanClassName() != null) { // van be null for factory methods
                        final Class<?> beanClass = Class.forName(beanDefinition.getBeanClassName());
                        if (Component.class.isAssignableFrom(beanClass))
                            beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, beanName);
                    }
                } catch (Exception ex) {
                    LOG.error("Error loading bean " + beanName + " definition.", ex);
                    throw new Error(ex);
                }
            }
        }
    });

    if (beanFactoryPostProcessor != null)
        context.addBeanFactoryPostProcessor(beanFactoryPostProcessor);

    beanFactory.registerCustomEditor(org.w3c.dom.Element.class,
            co.paralleluniverse.common.util.DOMElementProprtyEditor.class);

    final Map<String, Object> beans = new HashMap<String, Object>();

    beanFactory.addBeanPostProcessor(new BeanPostProcessor() {
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            LOG.info("Loading bean {} [{}]", beanName, bean.getClass().getName());
            beans.put(beanName, bean);

            if (bean instanceof Service) {
                final BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
                Collection<String> dependencies = getBeanDependencies(beanDefinition);

                for (String dependeeName : dependencies) {
                    Object dependee = beanFactory.getBean(dependeeName);
                    if (dependee instanceof Service) {
                        ((Service) dependee).addDependedBy((Service) bean);
                        ((Service) bean).addDependsOn((Service) dependee);
                    }
                }
            }
            return bean;
        }

        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            LOG.info("Bean {} [{}] loaded", beanName, bean.getClass().getName());
            return bean;
        }
    });

    final XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) beanFactory);
    xmlReader.loadBeanDefinitions(xmlResource);

    // start container
    context.refresh();

    // Call .postInit() on all Components
    // There's probably a better way to do this
    try {
        for (Map.Entry<String, Object> entry : beans.entrySet()) {
            final String beanName = entry.getKey();
            final Object bean = entry.getValue();
            if (bean instanceof Component) {
                LOG.info("Performing post-initialization on bean {} [{}]", beanName, bean.getClass().getName());
                ((Component) bean).postInit();
            }
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }

    return context;
}

From source file:atunit.spring.SpringContainer.java

public Object createTest(Class<?> testClass, Map<Field, Object> fieldValues) throws Exception {

    GenericApplicationContext ctx = new GenericApplicationContext();

    for (Field field : fieldValues.keySet()) {

        Bean beanAnno = field.getAnnotation(Bean.class);

        AbstractBeanDefinition beandef = defineInstanceHolderFactoryBean(field.getType(),
                fieldValues.get(field));

        if ((beanAnno != null) && !beanAnno.value().equals("")) {
            ctx.registerBeanDefinition(beanAnno.value(), beandef);
        } else {/* w  w w  .ja v  a 2s .c o m*/
            BeanDefinitionReaderUtils.registerWithGeneratedName(beandef, ctx);
        }
    }

    loadBeanDefinitions(testClass, ctx);

    fillInMissingFieldBeans(testClass, ctx);

    ctx.refresh();

    Object test = testClass.newInstance();
    for (Field field : testClass.getDeclaredFields()) {
        field.setAccessible(true);
        Bean beanAnno = field.getAnnotation(Bean.class);
        if (beanAnno == null) {
            if (fieldValues.containsKey(field)) {
                field.set(test, fieldValues.get(field));
            }
        } else {
            if (!beanAnno.value().equals("")) {
                field.set(test, ctx.getBean(beanAnno.value()));
            } else {
                String[] beanNames = ctx.getBeanNamesForType(field.getType());
                if (beanNames.length < 1) {
                    throw new BeanCreationException("There are no beans defined with type " + field.getType());
                }
                if (beanNames.length > 1) {
                    throw new BeanCreationException(
                            "There are " + beanNames.length + " beans defined with type " + field.getType()
                                    + "; consider wiring by name instead");
                }
                field.set(test, ctx.getBean(beanNames[0]));
            }
        }
    }

    return test;
}

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

private GenericApplicationContext setupSqlSessionTemplate() {

    GenericApplicationContext genericApplicationContext = setupSqlSessionFactory();
    GenericBeanDefinition definition = new GenericBeanDefinition();
    definition.setBeanClass(SqlSessionTemplate.class);
    ConstructorArgumentValues constructorArgs = new ConstructorArgumentValues();
    constructorArgs.addGenericArgumentValue(new RuntimeBeanReference("sqlSessionFactory"));
    definition.setConstructorArgumentValues(constructorArgs);
    genericApplicationContext.registerBeanDefinition("sqlSessionTemplate", definition);
    return genericApplicationContext;
}