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

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

Introduction

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

Prototype

@Override
    public void refresh() throws BeansException, IllegalStateException 

Source Link

Usage

From source file:org.jasypt.spring31.annotation.EncryptablePropertySourcePostProcessorTest.java

/**
 * Tests the LIFO behavior of @EncryptablePropertySource annotaitons. The
 * last one registered should 'win'./*from ww  w. j  a  va 2  s .  c o  m*/
 */
@Test
public void orderingIsLifo() {
    {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.register(ConfigWithImplicitName.class, P2Config.class);
        ctx.refresh();
        // p2 should 'win' as it was registered last
        assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p2TestBean"));
        ctx.close();
    }

    {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.register(P2Config.class, ConfigWithImplicitName.class);
        ctx.refresh();
        // p1 should 'win' as it was registered last
        assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean"));
        ctx.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  a2 s .  c o  m*/
    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:pl.bristleback.server.bristle.conf.runner.ServerInstanceResolver.java

public BristlebackServerInstance resolverServerInstance() {
    InitialConfiguration initialConfiguration = initialConfigurationResolver.resolveConfiguration();
    startLogger(initialConfiguration);//from  www.j a  va 2 s.co m

    AnnotationConfigApplicationContext frameworkContext = new AnnotationConfigApplicationContext();
    BristleSpringIntegration springIntegration = new BristleSpringIntegration(actualApplicationContext,
            frameworkContext);
    BristlebackBeanFactoryPostProcessor bristlebackPostProcessor = new BristlebackBeanFactoryPostProcessor(
            initialConfiguration, springIntegration);
    frameworkContext.addBeanFactoryPostProcessor(bristlebackPostProcessor);
    frameworkContext.register(SpringConfigurationResolver.class);
    frameworkContext.scan(InitialConfiguration.SYSTEM_BASE_PACKAGES);
    frameworkContext.refresh();

    BristlebackConfig configuration = frameworkContext.getBean("bristlebackConfigurationFinal",
            BristlebackConfig.class);
    return new BristlebackServerInstance(configuration);
}

From source file:org.jasypt.spring31.annotation.EncryptablePropertySourcePostProcessorTest.java

@Test
public void withResolvablePlaceholder() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(ConfigWithResolvablePlaceholder.class);
    System.setProperty("path.to.properties", "org/jasypt/spring31/annotation");
    ctx.refresh();
    assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean"));
    System.clearProperty("path.to.properties");
    ctx.close();/*from   w  w w.jav a2 s  .  co  m*/

}

From source file:org.jasypt.spring31.annotation.EncryptablePropertySourcePostProcessorTest.java

@Test
public void withResolvablePlaceholderAndFactoryBean() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(ConfigWithResolvablePlaceholderAndFactoryBean.class);
    System.setProperty("path.to.properties", "org/jasypt/spring31/annotation");
    ctx.refresh();
    assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean"));
    System.clearProperty("path.to.properties");
    ctx.close();//  w w w  .  java  2s  .co  m

}

From source file:org.zenoss.zep.impl.PluginServiceImpl.java

public void initializePlugins() {
    if (!initializedPlugins.compareAndSet(false, true)) {
        return;/* ww  w  .j ava  2 s.c o m*/
    }
    if (this.pluginClassLoader != null) {
        // Create a child ApplicationContext to use to load plug-ins with the plug-in class loader.
        final ClassLoader current = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(this.pluginClassLoader);
        try {
            AnnotationConfigApplicationContext pluginApplicationContext = new AnnotationConfigApplicationContext();
            pluginApplicationContext.setId("Plug-in Application Context");
            pluginApplicationContext.setClassLoader(this.pluginClassLoader);
            pluginApplicationContext.setParent(this.applicationContext);
            pluginApplicationContext.scan("org.zenoss", "com.zenoss", "zenpacks");
            pluginApplicationContext.refresh();
            loadPlugins(pluginApplicationContext);
        } catch (RuntimeException e) {
            logger.warn("Failed to configure plug-in application context", e);
            throw e;
        } finally {
            Thread.currentThread().setContextClassLoader(current);
        }
    } else {
        // Load plug-ins using the primary application context - no plug-ins were found on the classpath.
        loadPlugins(this.applicationContext);
    }
}

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 . ja  va2 s. co  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: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();

    return context;
}

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.  j  a 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.finra.dm.tools.common.databridge.DataBridgeApp.java

/**
 * Creates and returns the Spring application context.
 *
 * @return the application context//from ww  w .jav  a  2  s  .com
 */
protected ApplicationContext createApplicationContext() {
    // Create the Spring application context and register the JavaConfig classes we need.
    // We will use core (in case it's needed), the service aspect that times the duration of the service method calls, and our specific beans defined in
    // the data bridge configuration. We're not including full service and DAO configurations because they come with database/data source dependencies
    // that we don't need and don't want (i.e. we don't want the database to be running as a pre-requisite for running the uploader).
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
    ApplicationContextHolder.setApplicationContext(applicationContext);
    applicationContext.register(CoreSpringModuleConfig.class, ServiceBasicAopSpringModuleConfig.class,
            DataBridgeSpringModuleConfig.class, DataBridgeEnvSpringModuleConfig.class);
    applicationContext.refresh();
    return applicationContext;
}