Example usage for org.springframework.context.annotation AnnotationConfigApplicationContext getBeanFactory

List of usage examples for org.springframework.context.annotation AnnotationConfigApplicationContext getBeanFactory

Introduction

In this page you can find the example usage for org.springframework.context.annotation AnnotationConfigApplicationContext getBeanFactory.

Prototype

@Override
public final ConfigurableListableBeanFactory getBeanFactory() 

Source Link

Document

Return the single internal BeanFactory held by this context (as ConfigurableListableBeanFactory).

Usage

From source file:com.avanza.ymer.MirrorEnvironment.java

public ApplicationContext getMongoClientContext() {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.getBeanFactory().registerSingleton("mongoDbFactory",
            new SimpleMongoDbFactory(mongoServer.getMongo(), TEST_MIRROR_DB_NAME));
    context.refresh();/*ww w.  ja  v  a2  s. com*/
    return context;
}

From source file:example.tests.InitialLoadTest.java

private ApplicationContext createSingleInstanceAppContext(MongoClient mongo) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.getBeanFactory().registerSingleton("mongoClient", new SimpleMongoDbFactory(mongo, "exampleDb"));
    context.refresh();//  w  ww  .  j ava  2 s  .  c  o  m
    return context;
}

From source file:at.ac.univie.isc.asio.nest.D2rqNestAssemblerTest.java

@Test
public void should_create_singleton_assembler_if_no_optional_listeners_present() throws Exception {
    final StaticApplicationContext parent = new StaticApplicationContext();
    final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.getBeanFactory().registerSingleton("factory", new SpringContextFactory(parent));
    context.register(D2rqNestAssembler.class);
    context.refresh();/*from w w  w.j a v a  2 s .c o  m*/
    final D2rqNestAssembler actual = context.getBean(D2rqNestAssembler.class);
    assertThat(actual, notNullValue());
}

From source file:at.ac.univie.isc.asio.nest.D2rqNestAssembler.java

final void inject(final AnnotationConfigApplicationContext context, final NestConfig config) {
    context.register(NestBluePrint.class);
    final ConfigurableListableBeanFactory beans = context.getBeanFactory();
    beans.registerSingleton("container-cleanup", new ContainerCleanUp(context, config, cleaners));
    beans.registerSingleton("dataset", config.getDataset());
    beans.registerSingleton("jdbc", config.getJdbc());
    beans.registerSingleton("d2rq", config.getD2rq());
}

From source file:com.doctor.spring4.blog.code.WireObjectDependenciesOutsideSpring.java

/**
 * ??spring??//from   w  ww  .j a  v a  2s .  co  m
 * 
 * @see http://www.javacodegeeks.com/2012/03/integrating-spring-into-legacy.html
 * 
 */
@Test
public void test_registerSingleton() {
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(
            SpringConfig.class);
    Person person = new Person();
    assertNull(person.getContext());

    applicationContext.getBeanFactory().registerSingleton("person", person);
    assertNotNull(applicationContext.getBean(Person.class));

    assertNull(person.getContext());

    applicationContext.getAutowireCapableBeanFactory().autowireBean(person);
    assertNotNull(person.getContext());
    Stream.of(applicationContext.getBeanDefinitionNames()).forEach(System.out::println);

    applicationContext.close();
}

From source file:com.visural.domo.spring.TransactionImplTest.java

private AnnotationConfigApplicationContext springBootstrap(ConnectionSource source)
        throws BeansException, IllegalStateException {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.register(AnnotationAwareAspectJAutoProxyCreator.class);
    CustomScopeConfigurer conf = new CustomScopeConfigurer();
    Map<String, Object> scopes = new HashMap<String, Object>();
    TransactionScope scope = new TransactionScope();
    scopes.put(TransactionScope.Name, scope);
    conf.setScopes(scopes);//from w ww.ja  v  a2s.c  om
    context.getBeanFactory().registerSingleton("transactionScope", scope);
    context.addBeanFactoryPostProcessor(conf);
    context.scan("com.visural");
    context.refresh();
    context.getBean(TransactionConfig.class).getConnectionProvider().registerDefaultConnectionSource(source);
    return context;
}

From source file:io.gravitee.gateway.handlers.api.ApiContextHandlerFactory.java

AbstractApplicationContext createApplicationContext(Api api) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.setParent(gatewayApplicationContext);
    context.setClassLoader(new ReactorHandlerClassLoader(gatewayApplicationContext.getClassLoader()));
    context.setEnvironment((ConfigurableEnvironment) gatewayApplicationContext.getEnvironment());

    PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
    configurer.setIgnoreUnresolvablePlaceholders(true);
    configurer.setEnvironment(gatewayApplicationContext.getEnvironment());
    context.addBeanFactoryPostProcessor(configurer);

    context.getBeanFactory().registerSingleton("api", api);
    context.register(ApiHandlerConfiguration.class);
    context.setId("context-api-" + api.getName());
    context.refresh();/* ww  w  .  j a  v  a  2s  . c  o  m*/

    return context;
}

From source file:org.jacpfx.vertx.spring.SpringVerticleFactory.java

private Verticle createSpringVerticle(final Class<?> currentVerticleClass, ClassLoader classLoader) {
    final SpringVerticle annotation = currentVerticleClass.getAnnotation(SpringVerticle.class);
    final Class<?> springConfigClass = annotation.springConfig();

    // Create the parent context  
    final GenericApplicationContext genericApplicationContext = new GenericApplicationContext();
    genericApplicationContext.setClassLoader(classLoader);
    if (parentContext != null) {
        genericApplicationContext.setParent(parentContext);
    }/*from ww  w. j  a v  a2s  . c  o m*/
    genericApplicationContext.refresh();
    genericApplicationContext.start();

    // 1. Create a new context for each verticle and use the specified spring configuration class if possible
    AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
    annotationConfigApplicationContext.setParent(genericApplicationContext);
    annotationConfigApplicationContext.register(SpringContextConfiguration.class, springConfigClass);

    // 2. Register a bean definition for this verticle
    annotationConfigApplicationContext.registerBeanDefinition(currentVerticleClass.getSimpleName(),
            new VerticleBeanDefinition(currentVerticleClass));

    // 3. Add a bean factory post processor to avoid configuration issues
    annotationConfigApplicationContext
            .addBeanFactoryPostProcessor(new SpringSingleVerticleConfiguration(currentVerticleClass));
    annotationConfigApplicationContext.refresh();
    annotationConfigApplicationContext.start();
    annotationConfigApplicationContext.registerShutdownHook();

    // 5. Return the verticle by fetching the bean from the context
    return (Verticle) annotationConfigApplicationContext.getBeanFactory()
            .getBean(currentVerticleClass.getSimpleName());
}

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/>/*from   w w w .  ja  v a2 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.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializerTests.java

@Test
public void logsOutput() throws Exception {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    this.initializer.initialize(context);
    context.register(Config.class);
    ConditionEvaluationReport.get(context.getBeanFactory()).recordExclusions(Arrays.asList("com.foo.Bar"));
    context.refresh();/* w ww  .jav a 2  s . c o m*/
    this.initializer.onApplicationEvent(new ContextRefreshedEvent(context));
    for (String message : this.debugLog) {
        System.out.println(message);
    }
    // Just basic sanity check, test is for visual inspection
    String l = this.debugLog.get(0);
    assertThat(l, containsString("not a web application (OnWebApplicationCondition)"));
}