Search in sources :

Example 61 with ConfigurableListableBeanFactory

use of org.springframework.beans.factory.config.ConfigurableListableBeanFactory in project spring-framework by spring-projects.

the class XmlWebApplicationContextTests method createContext.

@Override
protected ConfigurableApplicationContext createContext() throws Exception {
    InitAndIB.constructed = false;
    root = new XmlWebApplicationContext();
    root.getEnvironment().addActiveProfile("rootProfile1");
    MockServletContext sc = new MockServletContext("");
    root.setServletContext(sc);
    root.setConfigLocations(new String[] { "/org/springframework/web/context/WEB-INF/applicationContext.xml" });
    root.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {

        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            beanFactory.addBeanPostProcessor(new BeanPostProcessor() {

                @Override
                public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
                    if (bean instanceof TestBean) {
                        ((TestBean) bean).getFriends().add("myFriend");
                    }
                    return bean;
                }

                @Override
                public Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
                    return bean;
                }
            });
        }
    });
    root.refresh();
    XmlWebApplicationContext wac = new XmlWebApplicationContext();
    wac.getEnvironment().addActiveProfile("wacProfile1");
    wac.setParent(root);
    wac.setServletContext(sc);
    wac.setNamespace("test-servlet");
    wac.setConfigLocations(new String[] { "/org/springframework/web/context/WEB-INF/test-servlet.xml" });
    wac.refresh();
    return wac;
}
Also used : XmlWebApplicationContext(org.springframework.web.context.support.XmlWebApplicationContext) TestBean(org.springframework.tests.sample.beans.TestBean) BeanPostProcessor(org.springframework.beans.factory.config.BeanPostProcessor) MockServletContext(org.springframework.mock.web.test.MockServletContext) BeanFactoryPostProcessor(org.springframework.beans.factory.config.BeanFactoryPostProcessor) ConfigurableListableBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory)

Example 62 with ConfigurableListableBeanFactory

use of org.springframework.beans.factory.config.ConfigurableListableBeanFactory in project spring-framework by spring-projects.

the class LiveBeansView method generateJson.

/**
	 * Actually generate a JSON snapshot of the beans in the given ApplicationContexts.
	 * <p>This implementation doesn't use any JSON parsing libraries in order to avoid
	 * third-party library dependencies. It produces an array of context description
	 * objects, each containing a context and parent attribute as well as a beans
	 * attribute with nested bean description objects. Each bean object contains a
	 * bean, scope, type and resource attribute, as well as a dependencies attribute
	 * with a nested array of bean names that the present bean depends on.
	 * @param contexts the set of ApplicationContexts
	 * @return the JSON document
	 */
protected String generateJson(Set<ConfigurableApplicationContext> contexts) {
    StringBuilder result = new StringBuilder("[\n");
    for (Iterator<ConfigurableApplicationContext> it = contexts.iterator(); it.hasNext(); ) {
        ConfigurableApplicationContext context = it.next();
        result.append("{\n\"context\": \"").append(context.getId()).append("\",\n");
        if (context.getParent() != null) {
            result.append("\"parent\": \"").append(context.getParent().getId()).append("\",\n");
        } else {
            result.append("\"parent\": null,\n");
        }
        result.append("\"beans\": [\n");
        ConfigurableListableBeanFactory bf = context.getBeanFactory();
        String[] beanNames = bf.getBeanDefinitionNames();
        boolean elementAppended = false;
        for (String beanName : beanNames) {
            BeanDefinition bd = bf.getBeanDefinition(beanName);
            if (isBeanEligible(beanName, bd, bf)) {
                if (elementAppended) {
                    result.append(",\n");
                }
                result.append("{\n\"bean\": \"").append(beanName).append("\",\n");
                result.append("\"aliases\": ");
                appendArray(result, bf.getAliases(beanName));
                result.append(",\n");
                String scope = bd.getScope();
                if (!StringUtils.hasText(scope)) {
                    scope = BeanDefinition.SCOPE_SINGLETON;
                }
                result.append("\"scope\": \"").append(scope).append("\",\n");
                Class<?> beanType = bf.getType(beanName);
                if (beanType != null) {
                    result.append("\"type\": \"").append(beanType.getName()).append("\",\n");
                } else {
                    result.append("\"type\": null,\n");
                }
                result.append("\"resource\": \"").append(getEscapedResourceDescription(bd)).append("\",\n");
                result.append("\"dependencies\": ");
                appendArray(result, bf.getDependenciesForBean(beanName));
                result.append("\n}");
                elementAppended = true;
            }
        }
        result.append("]\n");
        result.append("}");
        if (it.hasNext()) {
            result.append(",\n");
        }
    }
    result.append("]");
    return result.toString();
}
Also used : ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) ConfigurableListableBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory)

Example 63 with ConfigurableListableBeanFactory

use of org.springframework.beans.factory.config.ConfigurableListableBeanFactory in project oap by oaplatform.

the class OapService method start.

@PostConstruct
public void start() {
    try {
        log.info("config = {}, config-directory = {}", config, confd);
        kernel = new Kernel(Module.CONFIGURATION.urlsFromClassPath());
        kernel.start(config, confd);
        val factory = (ConfigurableListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
        for (val entry : Application.kernel(Kernel.DEFAULT)) {
            log.trace("oap bean {}...", entry.getKey());
            factory.registerSingleton(entry.getKey(), entry.getValue());
        }
        log.debug("started");
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw e;
    }
}
Also used : lombok.val(lombok.val) ConfigurableListableBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) PostConstruct(javax.annotation.PostConstruct)

Example 64 with ConfigurableListableBeanFactory

use of org.springframework.beans.factory.config.ConfigurableListableBeanFactory in project pentaho-platform by pentaho.

the class DefaultPluginManager method getNativeBeanFactory.

/**
 * The native bean factory is the bean factory that has had all of its bean definitions loaded natively. In other
 * words, the plugin manager will not add any further bean definitions (i.e. from a plugin.xml file) into this
 * factory. This factory represents the one responsible for holding bean definitions for plugin.spring.xml or, if in a
 * unit test environment, the unit test pre-loaded bean factory.
 *
 * @return a bean factory will preconfigured bean definitions or <code>null</code> if no bean definition source is
 * available
 */
protected BeanFactory getNativeBeanFactory(final IPlatformPlugin plugin, final ClassLoader loader) {
    BeanFactory nativeFactory = null;
    if (plugin.getBeanFactory() != null) {
        // then we are probably in a unit test so just use the preconfigured one
        BeanFactory testFactory = plugin.getBeanFactory();
        if (testFactory instanceof ConfigurableBeanFactory) {
            ((ConfigurableBeanFactory) testFactory).setBeanClassLoader(loader);
        } else {
            // $NON-NLS-1$
            logger.warn(Messages.getInstance().getString("PluginManager.WARN_WRONG_BEAN_FACTORY_TYPE"));
        }
        nativeFactory = testFactory;
    } else {
        // $NON-NLS-1$
        File f = new File(((PluginClassLoader) loader).getPluginDir(), "plugin.spring.xml");
        if (f.exists()) {
            // $NON-NLS-1$
            logger.debug("Found plugin spring file @ " + f.getAbsolutePath());
            FileSystemResource fsr = new FileSystemResource(f);
            GenericApplicationContext appCtx = new GenericApplicationContext() {

                @Override
                protected void prepareBeanFactory(ConfigurableListableBeanFactory clBeanFactory) {
                    super.prepareBeanFactory(clBeanFactory);
                    clBeanFactory.setBeanClassLoader(loader);
                }

                @Override
                public ClassLoader getClassLoader() {
                    return loader;
                }
            };
            XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(appCtx);
            xmlReader.setBeanClassLoader(loader);
            xmlReader.loadBeanDefinitions(fsr);
            nativeFactory = appCtx;
        }
    }
    return nativeFactory;
}
Also used : ConfigurableBeanFactory(org.springframework.beans.factory.config.ConfigurableBeanFactory) GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) XmlBeanDefinitionReader(org.springframework.beans.factory.xml.XmlBeanDefinitionReader) ConfigurableListableBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) ListableBeanFactory(org.springframework.beans.factory.ListableBeanFactory) BeanFactory(org.springframework.beans.factory.BeanFactory) ConfigurableBeanFactory(org.springframework.beans.factory.config.ConfigurableBeanFactory) FileSystemResource(org.springframework.core.io.FileSystemResource) File(java.io.File) ConfigurableListableBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory)

Example 65 with ConfigurableListableBeanFactory

use of org.springframework.beans.factory.config.ConfigurableListableBeanFactory in project spring-cloud-config by spring-cloud.

the class OnSearchPathLocatorPresent method getMatchOutcome.

@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
    ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
    List<String> types = CompositeUtils.getCompositeTypeList(context.getEnvironment());
    // get EnvironmentRepository types from registered factories
    List<Class<? extends EnvironmentRepository>> repositoryTypes = new ArrayList<>();
    for (String type : types) {
        String factoryName = CompositeUtils.getFactoryName(type, beanFactory);
        Type[] actualTypeArguments = CompositeUtils.getEnvironmentRepositoryFactoryTypeParams(beanFactory, factoryName);
        Class<? extends EnvironmentRepository> repositoryType = (Class<? extends EnvironmentRepository>) actualTypeArguments[0];
        repositoryTypes.add(repositoryType);
    }
    boolean required = metadata.isAnnotated(ConditionalOnSearchPathLocator.class.getName());
    boolean foundSearchPathLocator = repositoryTypes.stream().anyMatch(SearchPathLocator.class::isAssignableFrom);
    if (required && !foundSearchPathLocator) {
        return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnSearchPathLocator.class).notAvailable(SearchPathLocator.class.getTypeName()));
    }
    if (!required && foundSearchPathLocator) {
        return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnMissingSearchPathLocator.class).available(SearchPathLocator.class.getTypeName()));
    }
    return ConditionOutcome.match();
}
Also used : EnvironmentRepository(org.springframework.cloud.config.server.environment.EnvironmentRepository) SearchPathLocator(org.springframework.cloud.config.server.environment.SearchPathLocator) ArrayList(java.util.ArrayList) Type(java.lang.reflect.Type) ConfigurableListableBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory)

Aggregations

ConfigurableListableBeanFactory (org.springframework.beans.factory.config.ConfigurableListableBeanFactory)104 Test (org.junit.Test)16 Test (org.junit.jupiter.api.Test)15 NoSuchBeanDefinitionException (org.springframework.beans.factory.NoSuchBeanDefinitionException)13 GenericApplicationContext (org.springframework.context.support.GenericApplicationContext)12 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)10 ConfigurableApplicationContext (org.springframework.context.ConfigurableApplicationContext)10 ApplicationContext (org.springframework.context.ApplicationContext)9 BeanDefinitionRegistry (org.springframework.beans.factory.support.BeanDefinitionRegistry)8 GenericBeanDefinition (org.springframework.beans.factory.support.GenericBeanDefinition)7 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)7 XmlWebApplicationContext (org.springframework.web.context.support.XmlWebApplicationContext)7 Map (java.util.Map)6 BeanFactory (org.springframework.beans.factory.BeanFactory)6 ListableBeanFactory (org.springframework.beans.factory.ListableBeanFactory)6 Collectors (java.util.stream.Collectors)5 DefaultListableBeanFactory (org.springframework.beans.factory.support.DefaultListableBeanFactory)5 HashMap (java.util.HashMap)4 BeanFactoryPostProcessor (org.springframework.beans.factory.config.BeanFactoryPostProcessor)4 SimpleApplicationEventMulticaster (org.springframework.context.event.SimpleApplicationEventMulticaster)4