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:de.rkl.tools.tzconv.TimezoneConverter.java

private ApplicationContext initializeSpringContext() {
    final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.scan(TimezoneConverter.class.getPackage().getName());
    context.refresh();
    return context;
}

From source file:com.solace.labs.spring.boot.autoconfigure.SolaceJavaAutoConfigurationTest.java

private void load(Class<?> config, String... environment) {
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
    EnvironmentTestUtils.addEnvironment(applicationContext, environment);
    applicationContext.register(config);
    applicationContext.register(SolaceJavaAutoConfiguration.class);
    applicationContext.refresh();
    this.context = applicationContext;
}

From source file:org.exoplatform.container.spring.AnnotationConfigApplicationContextProvider.java

/**
 * {@inheritDoc}/*from  ww w . ja  v  a  2s  .c om*/
 */
public ApplicationContext getApplicationContext(ApplicationContext parent) {
    try {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.setParent(parent);
        for (String value : params.getValues()) {
            Class<?> clazz = ClassLoading.forName(value, AnnotationConfigApplicationContextProvider.class);
            ctx.register(clazz);
        }
        ctx.refresh();
        return ctx;
    } catch (Exception e) {
        throw new RuntimeException("Could not create the ApplicationContext", e);
    }
}

From source file:st.malike.service.storm.LNSBolt.java

@Override
public void prepare(Map stormConf, TopologyContext context) {
    try {/*ww  w. ja va  2 s  .co m*/
        this.config = stormConf;
        // reinitialize Spring IoC-- a hack
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.getEnvironment().getPropertySources()
                .addFirst(new ResourcePropertySource("classpath:application.properties"));
        ctx.scan("st.malike");
        ctx.refresh();
        demographicSummaryService = ctx.getBean(DemographicSummaryService.class);
        demographicService = ctx.getBean(DemographicService.class);
        summaryElasticSearchService = ctx.getBean(SummaryElasticSearchService.class);
        liveNotificationService = ctx.getBean(LiveNotificationService.class);
        summaryCalculatorService = ctx.getBean(SummaryCalculatorService.class);
    } catch (IOException ex) {
        Logger.getLogger(LNSBolt.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.ryantenney.metrics.spring.EnableMetricsTest.java

@Test
public void metricsConfigTest() throws Throwable {
    // Initialize the context
    AnnotationConfigApplicationContext applicationContext = null;
    try {//from  w w  w  .j  a v a  2 s . co  m
        applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.register(MetricsConfig.class);
        applicationContext.refresh();

        // Assert that the custom registries were used
        assertSame(metricRegistry, applicationContext.getBean(MetricRegistry.class));
        assertSame(healthCheckRegistry, applicationContext.getBean(HealthCheckRegistry.class));

        // Verify that the configureReporters method was invoked
        assertThat(MetricsConfig.isConfigureReportersInvoked, is(true));

        // Assert that the bean has been proxied
        TestBean testBean = applicationContext.getBean(TestBean.class);
        assertNotNull(testBean);
        assertThat(AopUtils.isAopProxy(testBean), is(true));

        // Verify that the Gauge field's value is returned
        Gauge<Integer> fieldGauge = (Gauge<Integer>) forGaugeField(metricRegistry, TestBean.class,
                "intGaugeField");
        assertNotNull(fieldGauge);
        assertThat(fieldGauge.getValue(), is(5));

        // Verify that the Gauge method's value is returned
        Gauge<Integer> methodGauge = (Gauge<Integer>) forGaugeMethod(metricRegistry, TestBean.class,
                "intGaugeMethod");
        assertNotNull(methodGauge);
        assertThat(methodGauge.getValue(), is(6));

        // Verify that the Timer's counter is incremented on method invocation
        Timer timedMethodTimer = forTimedMethod(metricRegistry, TestBean.class, "timedMethod");
        assertNotNull(timedMethodTimer);
        assertThat(timedMethodTimer.getCount(), is(0L));
        testBean.timedMethod();
        assertThat(timedMethodTimer.getCount(), is(1L));

        // Verify that the Meter's counter is incremented on method invocation
        Meter meteredMethodMeter = forMeteredMethod(metricRegistry, TestBean.class, "meteredMethod");
        assertNotNull(meteredMethodMeter);
        assertThat(meteredMethodMeter.getCount(), is(0L));
        testBean.meteredMethod();
        assertThat(meteredMethodMeter.getCount(), is(1L));

        // Verify that the Meter's counter is incremented on method invocation
        Meter exceptionMeteredMethodMeter = forExceptionMeteredMethod(metricRegistry, TestBean.class,
                "exceptionMeteredMethod");
        assertNotNull(exceptionMeteredMethodMeter);
        assertThat(exceptionMeteredMethodMeter.getCount(), is(0L));
        try {
            testBean.exceptionMeteredMethod();
        } catch (Throwable t) {
        }
        assertThat(exceptionMeteredMethodMeter.getCount(), is(1L));
    } finally {
        if (applicationContext != null) {
            applicationContext.close();
        }
    }
}

From source file:com.acme.ModuleConfigurationTest.java

@Test
public void test() {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    Properties properties = new Properties();
    properties.put("prefix", "foo");
    properties.put("suffix", "bar");
    context.getEnvironment().getPropertySources().addLast(new PropertiesPropertySource("options", properties));
    context.register(TestConfiguration.class);
    context.refresh();

    MessageChannel input = context.getBean("input", MessageChannel.class);
    SubscribableChannel output = context.getBean("output", SubscribableChannel.class);

    final AtomicBoolean handled = new AtomicBoolean();
    output.subscribe(new MessageHandler() {
        @Override//from ww  w .ja v  a 2  s.  c om
        public void handleMessage(Message<?> message) throws MessagingException {
            handled.set(true);
            assertEquals("foohellobar", message.getPayload());
        }
    });
    input.send(new GenericMessage<String>("hello"));
    assertTrue(handled.get());
}

From source file:com.arhs.spring.boot.autoconfigure.UnitTestBase.java

/**
 * Loads the configuration application context.
 *
 * @param configs     The configuration class.
 * @param environment The environment./*from  w w  w .j  a v  a  2 s .co m*/
 * @return A configuration application context.
 */
protected AnnotationConfigApplicationContext load(Class<?>[] configs, String... environment) {
    // Creates a instance of the "AnnotationConfigApplicationContext" class that represents
    // the application context.
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

    // Adds environment.
    EnvironmentTestUtils.addEnvironment(applicationContext, environment);

    // Registers the configuration class and auto-configuration classes.
    applicationContext.register(ConfigurationTest.class);
    applicationContext.register(configs);
    applicationContext.refresh();

    return applicationContext;
}

From source file:de.thischwa.pmcms.conf.BasicConfigurator.java

private void init() {
    if (System.getProperty("data.dir") == null)
        throw new IllegalArgumentException("No data directory set!");
    dataDir = new File(System.getProperty("data.dir"));
    if (!dataDir.exists())
        throw new IllegalArgumentException(
                String.format("Data directory not found: %s", dataDir.getAbsolutePath()));

    // load and merge the properties 
    loadProperties();/*  www.jav  a2s .com*/

    // build special props
    String baseUrl = String.format("http://%s:%s/", props.get("pmcms.jetty.host"),
            props.get("pmcms.jetty.port"));
    props.setProperty("baseurl", baseUrl);
    props.setProperty("data.dir", dataDir.getAbsolutePath());
    System.setProperty("content.types.user.table",
            new File(Constants.APPLICATION_DIR, "lib/content-types.properties").getAbsolutePath());

    // init log4j
    LogManager.resetConfiguration();
    PropertyConfigurator.configure(PropertiesTool.getProperties(props, "log4j"));
    Logger logger = Logger.getLogger(BasicConfigurator.class);
    logger.info("*** log4j initialized!");

    // init the spring framework
    try {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.scan("de.thischwa.pmcms");
        PropertySourcesPlaceholderConfigurer config = new PropertySourcesPlaceholderConfigurer();
        config.setProperties(props);
        config.postProcessBeanFactory(ctx.getDefaultListableBeanFactory());
        ctx.refresh();
        context = ctx;
        logger.info("*** Spring initialized!");
        PropertiesManager pm = context.getBean(PropertiesManager.class);
        pm.setProperties(props);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    logger.info("*** Basic configuration successful done.");
}

From source file:io.milton.servlet.SpringMiltonFilter.java

@SuppressWarnings("resource")
protected void initSpringApplicationContext(FilterConfig fc) {

    final WebApplicationContext rootContext = WebApplicationContextUtils
            .getWebApplicationContext(fc.getServletContext());

    StaticApplicationContext parent;// w w w . java  2 s. co m
    if (rootContext != null) {
        log.info("Found a root spring context, and using it");
        parent = new StaticApplicationContext(rootContext);
    } else {
        log.info("No root spring context");
        parent = new StaticApplicationContext();
    }

    final FilterConfigWrapper configWrapper = new FilterConfigWrapper(fc);
    parent.getBeanFactory().registerSingleton("config", configWrapper);
    parent.getBeanFactory().registerSingleton("servletContext", fc.getServletContext());
    File webRoot = new File(fc.getServletContext().getRealPath("/"));
    parent.getBeanFactory().registerSingleton("webRoot", webRoot);
    log.info("Registered root webapp path in: webroot=" + webRoot.getAbsolutePath());
    parent.refresh();

    final String configClass = fc.getInitParameter("contextConfigClass");
    final String sFiles = fc.getInitParameter("contextConfigLocation");

    ConfigurableApplicationContext ctx = null;
    if (StringUtils.isNotBlank(configClass)) {
        try {
            Class<?> clazz = Class.forName(configClass);
            final AnnotationConfigApplicationContext annotationCtx = new AnnotationConfigApplicationContext();
            annotationCtx.setParent(parent);
            annotationCtx.register(clazz);
            annotationCtx.refresh();
            ctx = annotationCtx;
        } catch (ClassNotFoundException e) {
            ctx = null;
            log.error("Unable to create a child context for Milton", e);
        }
    } else {
        String[] contextFiles;
        if (sFiles != null && sFiles.trim().length() > 0) {
            contextFiles = sFiles.split(" ");
        } else {
            contextFiles = new String[] { "applicationContext.xml" };
        }

        try {
            ctx = new ClassPathXmlApplicationContext(contextFiles, parent);
        } catch (BeansException e) {
            log.error("Unable to create a child context for Milton", e);
        }
    }

    if (ctx == null) {
        log.warn("No child context available, only using parent context");
        context = parent;
    } else {
        context = ctx;
    }

}

From source file:io.gravitee.gateway.policy.impl.processor.spring.SpringPolicyContextProviderFactory.java

public PolicyContextProvider create(PolicyContext policyContext) {
    Import importAnnotation = policyContext.getClass().getAnnotation(Import.class);

    List<Class<?>> importClasses = Arrays.asList(importAnnotation.value());

    LOGGER.info("Initializing a Spring context provider from @Import annotation: {}",
            String.join(",", importClasses.stream().map(Class::getName).collect(Collectors.toSet())));

    AnnotationConfigApplicationContext policyApplicationContext = new AnnotationConfigApplicationContext();
    policyApplicationContext.setClassLoader(policyContext.getClass().getClassLoader());
    importClasses.forEach(policyApplicationContext::register);

    // TODO: set the parent application context ?
    // pluginContext.setEnvironment(applicationContextParent.getEnvironment());
    // pluginContext.setParent(applicationContextParent);

    policyApplicationContext.refresh();
    return new SpringPolicyContextProvider(policyApplicationContext);
}