Search in sources :

Example 36 with ConfigurableApplicationContext

use of org.springframework.context.ConfigurableApplicationContext in project spring-framework by spring-projects.

the class ApplicationContextInitializerUtils method resolveInitializerClasses.

/**
	 * Resolve the set of merged {@code ApplicationContextInitializer} classes for the
	 * supplied list of {@code ContextConfigurationAttributes}.
	 *
	 * <p>Note that the {@link ContextConfiguration#inheritInitializers inheritInitializers}
	 * flag of {@link ContextConfiguration @ContextConfiguration} will be taken into
	 * consideration. Specifically, if the {@code inheritInitializers} flag is set to
	 * {@code true} for a given level in the class hierarchy represented by the provided
	 * configuration attributes, context initializer classes defined at the given level
	 * will be merged with those defined in higher levels of the class hierarchy.
	 *
	 * @param configAttributesList the list of configuration attributes to process; must
	 * not be {@code null} or <em>empty</em>; must be ordered <em>bottom-up</em>
	 * (i.e., as if we were traversing up the class hierarchy)
	 * @return the set of merged context initializer classes, including those from
	 * superclasses if appropriate (never {@code null})
	 * @since 3.2
	 */
static Set<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>> resolveInitializerClasses(List<ContextConfigurationAttributes> configAttributesList) {
    Assert.notEmpty(configAttributesList, "ContextConfigurationAttributes list must not be empty");
    final //
    Set<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>> initializerClasses = new HashSet<>();
    for (ContextConfigurationAttributes configAttributes : configAttributesList) {
        if (logger.isTraceEnabled()) {
            logger.trace(String.format("Processing context initializers for context configuration attributes %s", configAttributes));
        }
        initializerClasses.addAll(Arrays.asList(configAttributes.getInitializers()));
        if (!configAttributes.isInheritInitializers()) {
            break;
        }
    }
    return initializerClasses;
}
Also used : ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) ContextConfigurationAttributes(org.springframework.test.context.ContextConfigurationAttributes) ApplicationContextInitializer(org.springframework.context.ApplicationContextInitializer) HashSet(java.util.HashSet)

Example 37 with ConfigurableApplicationContext

use of org.springframework.context.ConfigurableApplicationContext in project spring-framework by spring-projects.

the class AbstractExpressionEvaluatingCondition method evaluateExpression.

private <A extends Annotation> boolean evaluateExpression(String expression, boolean loadContext, Class<A> annotationType, ExtensionContext extensionContext) {
    AnnotatedElement element = extensionContext.getElement().get();
    GenericApplicationContext gac = null;
    ApplicationContext applicationContext;
    if (loadContext) {
        applicationContext = SpringExtension.getApplicationContext(extensionContext);
    } else {
        gac = new GenericApplicationContext();
        gac.refresh();
        applicationContext = gac;
    }
    if (!(applicationContext instanceof ConfigurableApplicationContext)) {
        if (logger.isWarnEnabled()) {
            String contextType = (applicationContext != null ? applicationContext.getClass().getName() : "null");
            logger.warn(String.format("@%s(\"%s\") could not be evaluated on [%s] since the test " + "ApplicationContext [%s] is not a ConfigurableApplicationContext", annotationType.getSimpleName(), expression, element, contextType));
        }
        return false;
    }
    ConfigurableBeanFactory configurableBeanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
    BeanExpressionResolver expressionResolver = configurableBeanFactory.getBeanExpressionResolver();
    BeanExpressionContext beanExpressionContext = new BeanExpressionContext(configurableBeanFactory, null);
    Object result = expressionResolver.evaluate(configurableBeanFactory.resolveEmbeddedValue(expression), beanExpressionContext);
    if (gac != null) {
        gac.close();
    }
    if (result instanceof Boolean) {
        return ((Boolean) result).booleanValue();
    } else if (result instanceof String) {
        String str = ((String) result).trim().toLowerCase();
        if ("true".equals(str)) {
            return true;
        }
        Assert.state("false".equals(str), () -> String.format("@%s(\"%s\") on %s must evaluate to \"true\" or \"false\", not \"%s\"", annotationType.getSimpleName(), expression, element, result));
        return false;
    } else {
        String message = String.format("@%s(\"%s\") on %s must evaluate to a String or a Boolean, not %s", annotationType.getSimpleName(), expression, element, (result != null ? result.getClass().getName() : "null"));
        throw new IllegalStateException(message);
    }
}
Also used : ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) ConfigurableBeanFactory(org.springframework.beans.factory.config.ConfigurableBeanFactory) ApplicationContext(org.springframework.context.ApplicationContext) GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) BeanExpressionResolver(org.springframework.beans.factory.config.BeanExpressionResolver) GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) AnnotatedElement(java.lang.reflect.AnnotatedElement) BeanExpressionContext(org.springframework.beans.factory.config.BeanExpressionContext)

Example 38 with ConfigurableApplicationContext

use of org.springframework.context.ConfigurableApplicationContext in project spring-framework by spring-projects.

the class DefaultTestContext method getApplicationContext.

/**
	 * Get the {@linkplain ApplicationContext application context} for this
	 * test context.
	 * <p>The default implementation delegates to the {@link CacheAwareContextLoaderDelegate}
	 * that was supplied when this {@code TestContext} was constructed.
	 * @see CacheAwareContextLoaderDelegate#loadContext
	 * @throws IllegalStateException if the context returned by the context
	 * loader delegate is not <em>active</em> (i.e., has been closed).
	 */
public ApplicationContext getApplicationContext() {
    ApplicationContext context = this.cacheAwareContextLoaderDelegate.loadContext(this.mergedContextConfiguration);
    if (context instanceof ConfigurableApplicationContext) {
        @SuppressWarnings("resource") ConfigurableApplicationContext cac = (ConfigurableApplicationContext) context;
        Assert.state(cac.isActive(), () -> "The ApplicationContext loaded for [" + mergedContextConfiguration + "] is not active. This may be due to one of the following reasons: " + "1) the context was closed programmatically by user code; " + "2) the context was closed during parallel test execution either " + "according to @DirtiesContext semantics or due to automatic eviction " + "from the ContextCache due to a maximum cache size policy.");
    }
    return context;
}
Also used : ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) ApplicationContext(org.springframework.context.ApplicationContext)

Example 39 with ConfigurableApplicationContext

use of org.springframework.context.ConfigurableApplicationContext in project spring-framework by spring-projects.

the class AbstractGenericWebContextLoader method loadContext.

// --- SmartContextLoader -----------------------------------------------
/**
	 * Load a Spring {@link WebApplicationContext} from the supplied
	 * {@link MergedContextConfiguration}.
	 *
	 * <p>Implementation details:
	 *
	 * <ul>
	 * <li>Calls {@link #validateMergedContextConfiguration(WebMergedContextConfiguration)}
	 * to allow subclasses to validate the supplied configuration before proceeding.</li>
	 * <li>Creates a {@link GenericWebApplicationContext} instance.</li>
	 * <li>If the supplied {@code MergedContextConfiguration} references a
	 * {@linkplain MergedContextConfiguration#getParent() parent configuration},
	 * the corresponding {@link MergedContextConfiguration#getParentApplicationContext()
	 * ApplicationContext} will be retrieved and
	 * {@linkplain GenericWebApplicationContext#setParent(ApplicationContext) set as the parent}
	 * for the context created by this method.</li>
	 * <li>Delegates to {@link #configureWebResources} to create the
	 * {@link MockServletContext} and set it in the {@code WebApplicationContext}.</li>
	 * <li>Calls {@link #prepareContext} to allow for customizing the context
	 * before bean definitions are loaded.</li>
	 * <li>Calls {@link #customizeBeanFactory} to allow for customizing the
	 * context's {@code DefaultListableBeanFactory}.</li>
	 * <li>Delegates to {@link #loadBeanDefinitions} to populate the context
	 * from the locations or classes in the supplied {@code MergedContextConfiguration}.</li>
	 * <li>Delegates to {@link AnnotationConfigUtils} for
	 * {@linkplain AnnotationConfigUtils#registerAnnotationConfigProcessors registering}
	 * annotation configuration processors.</li>
	 * <li>Calls {@link #customizeContext} to allow for customizing the context
	 * before it is refreshed.</li>
	 * <li>{@link ConfigurableApplicationContext#refresh Refreshes} the
	 * context and registers a JVM shutdown hook for it.</li>
	 * </ul>
	 *
	 * @return a new web application context
	 * @see org.springframework.test.context.SmartContextLoader#loadContext(MergedContextConfiguration)
	 * @see GenericWebApplicationContext
	 */
@Override
public final ConfigurableApplicationContext loadContext(MergedContextConfiguration mergedConfig) throws Exception {
    Assert.isTrue(mergedConfig instanceof WebMergedContextConfiguration, () -> String.format("Cannot load WebApplicationContext from non-web merged context configuration %s. " + "Consider annotating your test class with @WebAppConfiguration.", mergedConfig));
    WebMergedContextConfiguration webMergedConfig = (WebMergedContextConfiguration) mergedConfig;
    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Loading WebApplicationContext for merged context configuration %s.", webMergedConfig));
    }
    validateMergedContextConfiguration(webMergedConfig);
    GenericWebApplicationContext context = new GenericWebApplicationContext();
    ApplicationContext parent = mergedConfig.getParentApplicationContext();
    if (parent != null) {
        context.setParent(parent);
    }
    configureWebResources(context, webMergedConfig);
    prepareContext(context, webMergedConfig);
    customizeBeanFactory(context.getDefaultListableBeanFactory(), webMergedConfig);
    loadBeanDefinitions(context, webMergedConfig);
    AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
    customizeContext(context, webMergedConfig);
    context.refresh();
    context.registerShutdownHook();
    return context;
}
Also used : WebApplicationContext(org.springframework.web.context.WebApplicationContext) ApplicationContext(org.springframework.context.ApplicationContext) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) GenericWebApplicationContext(org.springframework.web.context.support.GenericWebApplicationContext) GenericWebApplicationContext(org.springframework.web.context.support.GenericWebApplicationContext)

Example 40 with ConfigurableApplicationContext

use of org.springframework.context.ConfigurableApplicationContext in project spring-boot by spring-projects.

the class EmbeddedMongoAutoConfigurationTests method portIsAvailableInParentContext.

@Test
public void portIsAvailableInParentContext() {
    ConfigurableApplicationContext parent = new AnnotationConfigApplicationContext();
    parent.refresh();
    try {
        this.context = new AnnotationConfigApplicationContext();
        this.context.setParent(parent);
        this.context.register(EmbeddedMongoAutoConfiguration.class, MongoClientConfiguration.class);
        this.context.refresh();
        assertThat(parent.getEnvironment().getProperty("local.mongo.port")).isNotNull();
    } finally {
        parent.close();
    }
}
Also used : ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) AnnotationConfigApplicationContext(org.springframework.context.annotation.AnnotationConfigApplicationContext) Test(org.junit.Test)

Aggregations

ConfigurableApplicationContext (org.springframework.context.ConfigurableApplicationContext)177 Test (org.junit.Test)110 AnnotationConfigApplicationContext (org.springframework.context.annotation.AnnotationConfigApplicationContext)42 SpringApplicationBuilder (org.springframework.boot.builder.SpringApplicationBuilder)17 ApplicationContext (org.springframework.context.ApplicationContext)17 SpringApplication (org.springframework.boot.SpringApplication)14 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)13 ClassPathXmlApplicationContext (org.springframework.context.support.ClassPathXmlApplicationContext)13 DataSource (javax.sql.DataSource)8 ConfigurableEnvironment (org.springframework.core.env.ConfigurableEnvironment)7 JmsListenerContainerTestFactory (org.springframework.jms.config.JmsListenerContainerTestFactory)7 MBeanServer (javax.management.MBeanServer)6 ConfigurableListableBeanFactory (org.springframework.beans.factory.config.ConfigurableListableBeanFactory)6 Statement (java.sql.Statement)5 ArrayList (java.util.ArrayList)5 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)5 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)5 GenericApplicationContext (org.springframework.context.support.GenericApplicationContext)5 GenericXmlApplicationContext (org.springframework.context.support.GenericXmlApplicationContext)5 ObjectName (javax.management.ObjectName)4