Example usage for org.springframework.context ConfigurableApplicationContext getBeanFactory

List of usage examples for org.springframework.context ConfigurableApplicationContext getBeanFactory

Introduction

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

Prototype

ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;

Source Link

Document

Return the internal bean factory of this application context.

Usage

From source file:org.springframework.context.event.EventListenerMethodProcessor.java

@Override
public void afterSingletonsInstantiated() {
    List<EventListenerFactory> factories = getEventListenerFactories();
    ConfigurableApplicationContext context = getApplicationContext();
    String[] beanNames = context.getBeanNamesForType(Object.class);
    for (String beanName : beanNames) {
        if (!ScopedProxyUtils.isScopedTarget(beanName)) {
            Class<?> type = null;
            try {
                type = AutoProxyUtils.determineTargetClass(context.getBeanFactory(), beanName);
            } catch (Throwable ex) {
                // An unresolvable bean type, probably from a lazy bean - let's ignore it.
                if (logger.isDebugEnabled()) {
                    logger.debug("Could not resolve target class for bean with name '" + beanName + "'", ex);
                }/*from w ww  .  j  a v a  2 s  .co m*/
            }
            if (type != null) {
                if (ScopedObject.class.isAssignableFrom(type)) {
                    try {
                        Class<?> targetClass = AutoProxyUtils.determineTargetClass(context.getBeanFactory(),
                                ScopedProxyUtils.getTargetBeanName(beanName));
                        if (targetClass != null) {
                            type = targetClass;
                        }
                    } catch (Throwable ex) {
                        // An invalid scoped proxy arrangement - let's ignore it.
                        if (logger.isDebugEnabled()) {
                            logger.debug("Could not resolve target bean for scoped proxy '" + beanName + "'",
                                    ex);
                        }
                    }
                }
                try {
                    processBean(factories, beanName, type);
                } catch (Throwable ex) {
                    throw new BeanInitializationException("Failed to process @EventListener "
                            + "annotation on bean with name '" + beanName + "'", ex);
                }
            }
        }
    }
}

From source file:org.springframework.data.gemfire.config.annotation.support.GemFireComponentClassTypeScanner.java

/**
 * Returns a reference to the {@link ClassLoader} used to find and load GemFire application
 * persistent entity classes.//  ww w .ja v  a  2s.  c o m
 *
 * @return the {@link ClassLoader} used to find and load GemFire application persistent entity classes.
 * @see org.springframework.beans.factory.config.ConfigurableBeanFactory#getBeanClassLoader()
 * @see java.lang.Thread#getContextClassLoader()
 * @see java.lang.ClassLoader
 * @see #getApplicationContext()
 */
protected ClassLoader getEntityClassLoader() {

    ConfigurableApplicationContext applicationContext = getApplicationContext();

    return (this.entityClassLoader != null ? this.entityClassLoader
            : (applicationContext != null ? applicationContext.getBeanFactory().getBeanClassLoader()
                    : Thread.currentThread().getContextClassLoader()));
}

From source file:org.springframework.data.gemfire.test.GemfireTestApplicationContextInitializer.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    if (StringUtils.hasText(System.getProperty(GEMFIRE_TEST_RUNNER_DISABLED))) {
        String value = System.getProperty(GEMFIRE_TEST_RUNNER_DISABLED);

        if (!("NO".equalsIgnoreCase(value) || "FALSE".equalsIgnoreCase(value))) {
            logger.warn(String.format("Mocks disabled. Using real GemFire components: %1$s = %2$s",
                    GEMFIRE_TEST_RUNNER_DISABLED, value));
            return;
        }//from w w w .ja v a2 s .c om
    }

    applicationContext.getBeanFactory().addBeanPostProcessor(new GemfireTestBeanPostProcessor());
}

From source file:org.springframework.test.context.web.ServletTestExecutionListener.java

private void setUpRequestContextIfNecessary(TestContext testContext) {
    if (!isActivated(testContext) || alreadyPopulatedRequestContextHolder(testContext)) {
        return;/*  w  ww  .  j a  v a 2 s.c o m*/
    }

    ApplicationContext context = testContext.getApplicationContext();

    if (context instanceof WebApplicationContext) {
        WebApplicationContext wac = (WebApplicationContext) context;
        ServletContext servletContext = wac.getServletContext();
        Assert.state(servletContext instanceof MockServletContext, () -> String.format(
                "The WebApplicationContext for test context %s must be configured with a MockServletContext.",
                testContext));

        if (logger.isDebugEnabled()) {
            logger.debug(String.format(
                    "Setting up MockHttpServletRequest, MockHttpServletResponse, ServletWebRequest, and RequestContextHolder for test context %s.",
                    testContext));
        }

        MockServletContext mockServletContext = (MockServletContext) servletContext;
        MockHttpServletRequest request = new MockHttpServletRequest(mockServletContext);
        request.setAttribute(CREATED_BY_THE_TESTCONTEXT_FRAMEWORK, Boolean.TRUE);
        MockHttpServletResponse response = new MockHttpServletResponse();
        ServletWebRequest servletWebRequest = new ServletWebRequest(request, response);

        RequestContextHolder.setRequestAttributes(servletWebRequest);
        testContext.setAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
        testContext.setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);

        if (wac instanceof ConfigurableApplicationContext) {
            @SuppressWarnings("resource")
            ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) wac;
            ConfigurableListableBeanFactory bf = configurableApplicationContext.getBeanFactory();
            bf.registerResolvableDependency(MockHttpServletResponse.class, response);
            bf.registerResolvableDependency(ServletWebRequest.class, servletWebRequest);
        }
    }
}

From source file:org.springframework.test.context.web.WebTestExecutionListener.java

/**
 * TODO [SPR-9864] Document setUpRequestContext().
 *
 * @param testContext//  w w w  .j a v  a 2  s . c o  m
 * @param servletContext
 */
private void setUpRequestContextIfNecessary(TestContext testContext) {

    ApplicationContext context = testContext.getApplicationContext();

    if (context instanceof WebApplicationContext) {
        WebApplicationContext wac = (WebApplicationContext) context;
        ServletContext servletContext = wac.getServletContext();
        if (!(servletContext instanceof MockServletContext)) {
            throw new IllegalStateException(String.format(
                    "The WebApplicationContext for test context %s must be configured with a MockServletContext.",
                    testContext));
        }

        if (logger.isDebugEnabled()) {
            logger.debug(String.format(
                    "Setting up MockHttpServletRequest, MockHttpServletResponse, ServletWebRequest, and RequestContextHolder for test context %s.",
                    testContext));
        }

        if (RequestContextHolder.getRequestAttributes() == null) {
            MockServletContext mockServletContext = (MockServletContext) servletContext;
            MockHttpServletRequest request = new MockHttpServletRequest(mockServletContext);
            MockHttpServletResponse response = new MockHttpServletResponse();
            ServletWebRequest servletWebRequest = new ServletWebRequest(request, response);

            RequestContextHolder.setRequestAttributes(servletWebRequest);

            if (wac instanceof ConfigurableApplicationContext) {
                ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) wac;
                ConfigurableListableBeanFactory bf = configurableApplicationContext.getBeanFactory();
                bf.registerResolvableDependency(MockHttpServletResponse.class, response);
                bf.registerResolvableDependency(ServletWebRequest.class, servletWebRequest);
            }
        }
    }
}

From source file:org.springframework.web.reactive.result.method.annotation.ControllerMethodResolver.java

private void addResolversTo(ArgumentResolverRegistrar registrar, ReactiveAdapterRegistry reactiveRegistry,
        ConfigurableApplicationContext context) {

    ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();

    // Annotation-based...
    registrar.add(new RequestParamMethodArgumentResolver(beanFactory, reactiveRegistry, false));
    registrar.add(new RequestParamMapMethodArgumentResolver(reactiveRegistry));
    registrar.add(new PathVariableMethodArgumentResolver(beanFactory, reactiveRegistry));
    registrar.add(new PathVariableMapMethodArgumentResolver(reactiveRegistry));
    registrar.add(new MatrixVariableMethodArgumentResolver(beanFactory, reactiveRegistry));
    registrar.add(new MatrixVariableMapMethodArgumentResolver(reactiveRegistry));
    registrar.addIfRequestBody(readers -> new RequestBodyArgumentResolver(readers, reactiveRegistry));
    registrar.addIfRequestBody(readers -> new RequestPartMethodArgumentResolver(readers, reactiveRegistry));
    registrar.addIfModelAttribute(() -> new ModelAttributeMethodArgumentResolver(reactiveRegistry, false));
    registrar.add(new RequestHeaderMethodArgumentResolver(beanFactory, reactiveRegistry));
    registrar.add(new RequestHeaderMapMethodArgumentResolver(reactiveRegistry));
    registrar.add(new CookieValueMethodArgumentResolver(beanFactory, reactiveRegistry));
    registrar.add(new ExpressionValueMethodArgumentResolver(beanFactory, reactiveRegistry));
    registrar.add(new SessionAttributeMethodArgumentResolver(beanFactory, reactiveRegistry));
    registrar.add(new RequestAttributeMethodArgumentResolver(beanFactory, reactiveRegistry));

    // Type-based...
    registrar.addIfRequestBody(readers -> new HttpEntityArgumentResolver(readers, reactiveRegistry));
    registrar.add(new ModelArgumentResolver(reactiveRegistry));
    registrar.addIfModelAttribute(() -> new ErrorsMethodArgumentResolver(reactiveRegistry));
    registrar.add(new ServerWebExchangeArgumentResolver(reactiveRegistry));
    registrar.add(new PrincipalArgumentResolver(reactiveRegistry));
    registrar.addIfRequestBody(readers -> new SessionStatusMethodArgumentResolver());
    registrar.add(new WebSessionArgumentResolver(reactiveRegistry));

    // Custom...//from  w  ww.  j  ava2s .c o  m
    registrar.addCustomResolvers();

    // Catch-all...
    registrar.add(new RequestParamMethodArgumentResolver(beanFactory, reactiveRegistry, true));
    registrar.addIfModelAttribute(() -> new ModelAttributeMethodArgumentResolver(reactiveRegistry, true));
}

From source file:org.springframework.yarn.examples.XdAppmasterRunner.java

@Override
protected ConfigurableApplicationContext getChildApplicationContext(String configLocation,
        ConfigurableApplicationContext parent) {

    log.info("Using xd.transport=" + System.getProperty("xd.transport"));
    log.info("Using xd.store=" + System.getProperty("xd.store"));
    log.info("Using xd.home=" + System.getProperty("xd.home"));

    XmlWebApplicationContext context = new XmlWebApplicationContext();
    context.setConfigLocation("classpath:" + DefaultContainer.XD_INTERNAL_CONFIG_ROOT + "admin-server.xml");

    final StreamServer server = new StreamServer(context, 8282);
    server.afterPropertiesSet();//from  w  w w .j ava 2 s .  c om
    server.start();

    // when we get fix for 0-port trick in spring-xd
    //log.info("Streamserver tomcat port=" + server.getLocalPort());

    // context is already refreshed so just register singleton
    // not really a proper way to do it but serves the demo purpose
    // if streamserver could choose free port then below would
    // make much more sense
    parent.getBeanFactory().registerSingleton(YarnSystemConstants.DEFAULT_ID_AMTRACKSERVICE,
            new UrlAppmasterTrackService("http://localhost:" + server.getPort()));

    context.addApplicationListener(new ApplicationListener<ContextClosedEvent>() {
        @Override
        public void onApplicationEvent(ContextClosedEvent event) {
            server.stop();
        }
    });

    return context;
}