Example usage for org.springframework.context.support GenericApplicationContext refresh

List of usage examples for org.springframework.context.support GenericApplicationContext refresh

Introduction

In this page you can find the example usage for org.springframework.context.support GenericApplicationContext refresh.

Prototype

@Override
    public void refresh() throws BeansException, IllegalStateException 

Source Link

Usage

From source file:org.springframework.test.context.junit.jupiter.AbstractExpressionEvaluatingCondition.java

private <A extends Annotation> boolean evaluateExpression(String expression, boolean loadContext,
        Class<A> annotationType, ExtensionContext context) {

    Assert.state(context.getElement().isPresent(), "No AnnotatedElement");
    AnnotatedElement element = context.getElement().get();
    GenericApplicationContext gac = null;
    ApplicationContext applicationContext;

    if (loadContext) {
        applicationContext = SpringExtension.getApplicationContext(context);
    } else {/*from  w  w w .  j a va  2  s.co  m*/
        gac = new GenericApplicationContext();
        gac.refresh();
        applicationContext = gac;
    }

    if (!(applicationContext instanceof ConfigurableApplicationContext)) {
        if (logger.isWarnEnabled()) {
            String contextType = applicationContext.getClass().getName();
            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();
    Assert.state(expressionResolver != null, "No BeanExpressionResolver");
    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;
    } 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);
    }
}

From source file:org.springframework.test.context.support.AbstractGenericContextLoader.java

/**
 * Load a Spring ApplicationContext from the supplied {@link MergedContextConfiguration}.
 *
 * <p>Implementation details://from   ww w.  ja  va 2s  .co m
 *
 * <ul>
 * <li>Calls {@link #validateMergedContextConfiguration(MergedContextConfiguration)}
 * to allow subclasses to validate the supplied configuration before proceeding.</li>
 * <li>Creates a {@link GenericApplicationContext} 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 GenericApplicationContext#setParent(ApplicationContext) set as the parent}
 * for the context created by this method.</li>
 * <li>Calls {@link #prepareContext(GenericApplicationContext)} for backwards
 * compatibility with the {@link org.springframework.test.context.ContextLoader
 * ContextLoader} SPI.</li>
 * <li>Calls {@link #prepareContext(ConfigurableApplicationContext, MergedContextConfiguration)}
 * to allow for customizing the context before bean definitions are loaded.</li>
 * <li>Calls {@link #customizeBeanFactory(DefaultListableBeanFactory)} to allow for customizing the
 * context's {@code DefaultListableBeanFactory}.</li>
 * <li>Delegates to {@link #loadBeanDefinitions(GenericApplicationContext, MergedContextConfiguration)}
 * to populate the context from the locations or classes in the supplied
 * {@code MergedContextConfiguration}.</li>
 * <li>Delegates to {@link AnnotationConfigUtils} for
 * {@link AnnotationConfigUtils#registerAnnotationConfigProcessors registering}
 * annotation configuration processors.</li>
 * <li>Calls {@link #customizeContext(GenericApplicationContext)} to allow for customizing the context
 * before it is refreshed.</li>
 * <li>Calls {@link #customizeContext(ConfigurableApplicationContext, MergedContextConfiguration)} 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 application context
 * @see org.springframework.test.context.SmartContextLoader#loadContext(MergedContextConfiguration)
 * @see GenericApplicationContext
 * @since 3.1
 */
@Override
public final ConfigurableApplicationContext loadContext(MergedContextConfiguration mergedConfig)
        throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Loading ApplicationContext for merged context configuration [%s].",
                mergedConfig));
    }

    validateMergedContextConfiguration(mergedConfig);

    GenericApplicationContext context = new GenericApplicationContext();

    ApplicationContext parent = mergedConfig.getParentApplicationContext();
    if (parent != null) {
        context.setParent(parent);
    }
    prepareContext(context);
    prepareContext(context, mergedConfig);
    customizeBeanFactory(context.getDefaultListableBeanFactory());
    loadBeanDefinitions(context, mergedConfig);
    AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
    customizeContext(context);
    customizeContext(context, mergedConfig);
    context.refresh();
    context.registerShutdownHook();
    return context;
}

From source file:org.springframework.test.context.support.AbstractGenericContextLoader.java

/**
 * Load a Spring ApplicationContext from the supplied {@code locations}.
 *
 * <p>Implementation details://from   w w  w . java2s  . com
 *
 * <ul>
 * <li>Creates a {@link GenericApplicationContext} instance.</li>
 * <li>Calls {@link #prepareContext(GenericApplicationContext)} to allow for customizing the context
 * before bean definitions are loaded.</li>
 * <li>Calls {@link #customizeBeanFactory(DefaultListableBeanFactory)} to allow for customizing the
 * context's {@code DefaultListableBeanFactory}.</li>
 * <li>Delegates to {@link #createBeanDefinitionReader(GenericApplicationContext)} to create a
 * {@link BeanDefinitionReader} which is then used to populate the context
 * from the specified locations.</li>
 * <li>Delegates to {@link AnnotationConfigUtils} for
 * {@link AnnotationConfigUtils#registerAnnotationConfigProcessors registering}
 * annotation configuration processors.</li>
 * <li>Calls {@link #customizeContext(GenericApplicationContext)} 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>
 *
 * <p><b>Note</b>: this method does not provide a means to set active bean definition
 * profiles for the loaded context. See {@link #loadContext(MergedContextConfiguration)}
 * and {@link AbstractContextLoader#prepareContext(ConfigurableApplicationContext, MergedContextConfiguration)}
 * for an alternative.
 *
 * @return a new application context
 * @see org.springframework.test.context.ContextLoader#loadContext
 * @see GenericApplicationContext
 * @see #loadContext(MergedContextConfiguration)
 * @since 2.5
 */
@Override
public final ConfigurableApplicationContext loadContext(String... locations) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Loading ApplicationContext for locations [%s].",
                StringUtils.arrayToCommaDelimitedString(locations)));
    }
    GenericApplicationContext context = new GenericApplicationContext();
    prepareContext(context);
    customizeBeanFactory(context.getDefaultListableBeanFactory());
    createBeanDefinitionReader(context).loadBeanDefinitions(locations);
    AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
    customizeContext(context);
    context.refresh();
    context.registerShutdownHook();
    return context;
}

From source file:uk.co.modularaudio.util.spring.SpringComponentHelper.java

public GenericApplicationContext makeAppContext(final String beansResourcePath, final String configResourcePath,
        final String[] additionalBeansResources, final String[] additionalConfigResources)
        throws DatastoreException {
    GenericApplicationContext appContext = null;

    final Class<SpringComponentHelper> thisClass = SpringComponentHelper.class;

    // Do any work needed before we instantiate the context
    for (final SpringContextHelper helper : contextHelpers) {
        try {//from  w  ww . j a v  a  2 s.co  m
            helper.preContextDoThings();
        } catch (final Exception ce) {
            final String msg = "Exception caught calling precontext of helper " + helper.getClass() + ": "
                    + ce.toString();
            log.error(msg, ce);
            // Will halt context creation.
            throw new DatastoreException(msg, ce);
        }
    }

    try {
        final InputStream bIStream = thisClass.getResourceAsStream(beansResourcePath);
        if (bIStream != null) {
            final InputSource bISource = new InputSource(bIStream);

            appContext = new GenericApplicationContext();
            appContext.addBeanFactoryPostProcessor(beanInstantiationList);

            final XmlBeanDefinitionReader xbdr = new XmlBeanDefinitionReader(appContext);

            xbdr.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
            xbdr.loadBeanDefinitions(bISource);

            // And load any additional beans files now we've loaded the "driver"
            if (additionalBeansResources != null && additionalBeansResources.length > 0) {
                for (final String additionalBeansFilename : additionalBeansResources) {
                    InputStream aBiStream = null;
                    InputSource aBiSource = null;
                    try {
                        aBiStream = thisClass.getResourceAsStream(additionalBeansFilename);

                        if (aBiStream != null) {
                            aBiSource = new InputSource(aBiStream);
                            xbdr.loadBeanDefinitions(aBiSource);
                        } else {
                            throw new DatastoreException(
                                    "Failed to load additional services from file: " + additionalBeansFilename);
                        }
                    } finally {
                        if (aBiStream != null) {
                            aBiStream.close();
                        }
                    }
                }
            }

            final BeanDefinition bd = appContext.getBeanDefinition("configurationService");
            final MutablePropertyValues mpvs = bd.getPropertyValues();
            // Push in the configuration file if one needs to be set
            if (configResourcePath != null) {
                mpvs.removePropertyValue(CONFIG_RESOURCE_PATH_PROPERTY);
                mpvs.addPropertyValue(CONFIG_RESOURCE_PATH_PROPERTY, configResourcePath);

            }
            if (additionalConfigResources != null && additionalConfigResources.length > 0) {
                mpvs.removePropertyValue(ADDITIONAL_RESOURCE_PATHS);
                mpvs.addPropertyValue(ADDITIONAL_RESOURCE_PATHS, additionalConfigResources);
            }

            // Do any work needed before we refresh the context
            // Prerefresh
            for (final SpringContextHelper helper : contextHelpers) {
                try {
                    helper.preRefreshDoThings(appContext);
                } catch (final Exception prer) {
                    final String msg = "Exception caught calling prerefresh of helper " + helper.getClass()
                            + ": " + prer.toString();
                    log.error(msg, prer);
                    // Will halt context creation
                    throw new DatastoreException(msg, prer);
                }
            }

            appContext.refresh();

        } else {
            // Didn't find the beans file
            final String msg = "Unable to find beans file: " + beansResourcePath;
            log.error(msg);
            throw new DatastoreException(msg);
        }
    } catch (final Exception e) {
        final String msg = "Exception caught setting up app context: " + e.toString();
        log.error(msg, e);
        throw new DatastoreException(msg, e);
    }

    // Perform a GC pass here to clean up before things are launched post refresh
    Runtime.getRuntime().gc(); // NOPMD by dan on 30/07/15 15:00

    // Do any work needed after we refresh the context
    // Post refresh calls
    for (final SpringContextHelper helper : contextHelpers) {
        try {
            helper.postRefreshDoThings(appContext, beanInstantiationList);
        } catch (final Exception pre) {
            final String msg = "Exception caught calling postrefresh of helper " + helper.getClass() + ": "
                    + pre.toString();
            log.error(msg, pre);
            // Will halt context creation
            throw new DatastoreException(msg, pre);
        }
    }

    return appContext;
}