Example usage for org.springframework.beans.factory.config ConfigurableListableBeanFactory getBeanDefinitionNames

List of usage examples for org.springframework.beans.factory.config ConfigurableListableBeanFactory getBeanDefinitionNames

Introduction

In this page you can find the example usage for org.springframework.beans.factory.config ConfigurableListableBeanFactory getBeanDefinitionNames.

Prototype

String[] getBeanDefinitionNames();

Source Link

Document

Return the names of all beans defined in this factory.

Usage

From source file:org.springframework.amqp.rabbit.stocks.context.RefreshScope.java

/**
 * If the bean factory is a DefaultListableBeanFactory then it can serialize scoped beans and deserialize them in
 * another context (even in another JVM), as long as the ids of the bean factories match. This method sets up the
 * serialization id to be either the id provided to the scope instance, or if that is null, a hash of all the bean
 * names.//from  ww w . jav  a 2  s  .  co m
 * 
 * @param beanFactory the bean factory to configure
 */
private void setSerializationId(ConfigurableListableBeanFactory beanFactory) {

    if (beanFactory instanceof DefaultListableBeanFactory) {

        String id = this.id;
        if (id == null) {
            String names = Arrays.asList(beanFactory.getBeanDefinitionNames()).toString();
            logger.debug("Generating bean factory id from names: " + names);
            id = UUID.nameUUIDFromBytes(names.getBytes()).toString();
        }

        logger.info("BeanFactory id=" + id);
        ((DefaultListableBeanFactory) beanFactory).setSerializationId(id);

    } else {
        logger.warn("BeanFactory was not a DefaultListableBeanFactory, so RefreshScope beans "
                + "cannot be serialized reliably and passed to a remote JVM.");
    }

}

From source file:org.springframework.batch.core.partition.gemfire.RemoteScope.java

public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    beanFactory.registerScope(name, this);

    this.beanFactory = beanFactory;
    evaluationContext = new StandardEvaluationContext();
    evaluationContext.addPropertyAccessor(new BeanFactoryAccessor());

    Assert.state(beanFactory instanceof BeanDefinitionRegistry,
            "BeanFactory was not a BeanDefinitionRegistry, so RefreshScope cannot be used.");
    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

    String id = this.id;
    if (id == null) {
        String names = Arrays.asList(registry.getBeanDefinitionNames()).toString();
        logger.debug("Generating bean factory id from names: " + names);
        id = UUID.nameUUIDFromBytes(names.getBytes()).toString();
        logger.debug("Generated bean factory id: " + id);
    }//ww w  . j  av  a 2 s .  co m

    Assert.state(beanFactory instanceof BeanDefinitionRegistry,
            "BeanFactory was not a DefaultListableBeanFactory, so RefreshScope cannot be used.");
    ((DefaultListableBeanFactory) beanFactory).setSerializationId(id);

    for (String beanName : beanFactory.getBeanDefinitionNames()) {
        BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
        // Replace this or any of its inner beans with scoped proxy if it
        // has this scope
        boolean scoped = name.equals(definition.getScope());
        Scopifier scopifier = new Scopifier(registry, name, proxyTargetClass, scoped);
        scopifier.visitBeanDefinition(definition);
        if (scoped) {
            createScopedProxy(beanName, definition, registry, proxyTargetClass);
        }
    }

}

From source file:org.springframework.beans.factory.config.DeprecatedBeanWarner.java

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    if (isLogEnabled()) {
        String[] beanNames = beanFactory.getBeanDefinitionNames();
        for (String beanName : beanNames) {
            String nameToLookup = beanName;
            if (beanFactory.isFactoryBean(beanName)) {
                nameToLookup = BeanFactory.FACTORY_BEAN_PREFIX + beanName;
            }/* ww  w  .  j  a  va 2  s .  c  o m*/
            Class<?> beanType = beanFactory.getType(nameToLookup);
            if (beanType != null) {
                Class<?> userClass = ClassUtils.getUserClass(beanType);
                if (userClass.isAnnotationPresent(Deprecated.class)) {
                    BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
                    logDeprecatedBean(beanName, beanType, beanDefinition);
                }
            }
        }
    }
}

From source file:org.springframework.boot.autoconfigure.ComponentScanDetector.java

private void storeComponentScanBasePackages(ConfigurableListableBeanFactory beanFactory) {
    List<String> basePackages = new ArrayList<String>();
    for (String beanName : beanFactory.getBeanDefinitionNames()) {
        BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
        String[] basePackagesAttribute = (String[]) beanDefinition.getAttribute("componentScanBasePackages");
        if (basePackagesAttribute != null) {
            basePackages.addAll(Arrays.asList(basePackagesAttribute));
        }//from   w w  w  . j a va 2 s  .co  m
        AnnotationMetadata metadata = getMetadata(beanDefinition);
        basePackages.addAll(getBasePackages(metadata));
    }
    AutoConfigurationUtils.storeBasePackages(beanFactory, basePackages);
}

From source file:org.springframework.cloud.context.scope.GenericScope.java

public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    beanFactory.registerScope(name, this);
    setSerializationId(beanFactory);/*from   w w w. j a  v a2 s .  c  o  m*/

    this.beanFactory = beanFactory;

    evaluationContext = new StandardEvaluationContext();
    evaluationContext.addPropertyAccessor(new BeanFactoryAccessor());

    if (!autoProxy) {
        // No need to try and create proxies
        return;
    }

    Assert.state(beanFactory instanceof BeanDefinitionRegistry,
            "BeanFactory was not a BeanDefinitionRegistry, so RefreshScope cannot be used.");
    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

    for (String beanName : beanFactory.getBeanDefinitionNames()) {
        BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
        // Replace this or any of its inner beans with scoped proxy if it
        // has this scope
        boolean scoped = name.equals(definition.getScope());
        Scopifier scopifier = new Scopifier(registry, name, proxyTargetClass, scoped);
        scopifier.visitBeanDefinition(definition);
        if (scoped) {
            createScopedProxy(beanName, definition, registry, proxyTargetClass);
        }
    }

}

From source file:org.springframework.cloud.function.context.config.KotlinLambdaToFunctionAutoConfiguration.java

/**
 * Will transform all discovered Kotlin's Function1 and Function0 lambdas to java
 * Supplier, Function and Consumer, retaining the original Kotlin type
 * characteristics. In other words the resulting bean could be cast to both java and
 * kotlin types (i.e., java Function&lt;I,O&gt; vs. kotlin Function1&lt;I,O&gt;)
 * @return the bean factory post processor
 *///from   w  w  w . j a v a  2  s  .  com
@Bean
public BeanFactoryPostProcessor kotlinToFunctionTransformer() {
    return new BeanFactoryPostProcessor() {

        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

            String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
            for (String beanDefinitionName : beanDefinitionNames) {
                BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanDefinitionName);
                Object source = beanDefinition.getSource();
                if (source instanceof MethodMetadata) {
                    String returnTypeName = ((MethodMetadata) source).getReturnTypeName();
                    if (returnTypeName.startsWith("kotlin.jvm.functions.Function")) {
                        FunctionType functionType = new FunctionType(
                                FunctionContextUtils.findType(beanDefinitionName, beanFactory));
                        if (returnTypeName.equals("kotlin.jvm.functions.Function1")) {
                            if (Unit.class.isAssignableFrom(functionType.getOutputType())) {
                                KotlinLambdaToFunctionAutoConfiguration.this.logger
                                        .debug("Transforming Kotlin lambda " + beanDefinitionName
                                                + " to java Consumer");
                                this.register(beanDefinitionName, beanDefinition, KotlinConsumer.class,
                                        (BeanDefinitionRegistry) beanFactory);
                            } else {
                                KotlinLambdaToFunctionAutoConfiguration.this.logger
                                        .debug("Transforming Kotlin lambda " + beanDefinitionName
                                                + " to java Function");
                                this.register(beanDefinitionName, beanDefinition, KotlinFunction.class,
                                        (BeanDefinitionRegistry) beanFactory);
                            }
                        } else {
                            KotlinLambdaToFunctionAutoConfiguration.this.logger.debug(
                                    "Transforming Kotlin lambda " + beanDefinitionName + " to java Supplier");
                            this.register(beanDefinitionName, beanDefinition, KotlinSupplier.class,
                                    (BeanDefinitionRegistry) beanFactory);
                        }
                    }
                }
            }
        }

        private void register(String originalName, BeanDefinition originalDefinition, Class<?> clazz,
                BeanDefinitionRegistry registry) {
            RootBeanDefinition cbd = new RootBeanDefinition(clazz);
            ConstructorArgumentValues ca = new ConstructorArgumentValues();
            ca.addGenericArgumentValue(originalDefinition);
            cbd.setConstructorArgumentValues(ca);
            registry.removeBeanDefinition(originalName);
            registry.registerBeanDefinition(originalName, cbd);
        }
    };
}

From source file:org.springframework.context.annotation.ConfigurationClassPostProcessor.java

/**
 * Post-processes a BeanFactory in search of Configuration class BeanDefinitions;
 * any candidates are then enhanced by a {@link ConfigurationClassEnhancer}.
 * Candidate status is determined by BeanDefinition attribute metadata.
 * @see ConfigurationClassEnhancer/*from  ww  w. j  a v a 2s . c  om*/
 */
public void enhanceConfigurationClasses(ConfigurableListableBeanFactory beanFactory) {
    Map<String, AbstractBeanDefinition> configBeanDefs = new LinkedHashMap<>();
    for (String beanName : beanFactory.getBeanDefinitionNames()) {
        BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
        if (ConfigurationClassUtils.isFullConfigurationClass(beanDef)) {
            if (!(beanDef instanceof AbstractBeanDefinition)) {
                throw new BeanDefinitionStoreException("Cannot enhance @Configuration bean definition '"
                        + beanName + "' since it is not stored in an AbstractBeanDefinition subclass");
            } else if (logger.isWarnEnabled() && beanFactory.containsSingleton(beanName)) {
                logger.warn("Cannot enhance @Configuration bean definition '" + beanName
                        + "' since its singleton instance has been created too early. The typical cause "
                        + "is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor "
                        + "return type: Consider declaring such methods as 'static'.");
            }
            configBeanDefs.put(beanName, (AbstractBeanDefinition) beanDef);
        }
    }
    if (configBeanDefs.isEmpty()) {
        // nothing to enhance -> return immediately
        return;
    }

    ConfigurationClassEnhancer enhancer = new ConfigurationClassEnhancer();
    for (Map.Entry<String, AbstractBeanDefinition> entry : configBeanDefs.entrySet()) {
        AbstractBeanDefinition beanDef = entry.getValue();
        // If a @Configuration class gets proxied, always proxy the target class
        beanDef.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
        try {
            // Set enhanced subclass of the user-specified bean class
            Class<?> configClass = beanDef.resolveBeanClass(this.beanClassLoader);
            if (configClass != null) {
                Class<?> enhancedClass = enhancer.enhance(configClass, this.beanClassLoader);
                if (configClass != enhancedClass) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(String.format(
                                "Replacing bean definition '%s' existing class '%s' with "
                                        + "enhanced class '%s'",
                                entry.getKey(), configClass.getName(), enhancedClass.getName()));
                    }
                    beanDef.setBeanClass(enhancedClass);
                }
            }
        } catch (Throwable ex) {
            throw new IllegalStateException("Cannot load configuration class: " + beanDef.getBeanClassName(),
                    ex);
        }
    }
}

From source file:org.springframework.flex.config.HibernateSerializationConfigPostProcessor.java

private BeanDefinition findMessageBrokerFactoryBeanDefinition(ConfigurableListableBeanFactory beanFactory) {
    if (beanFactory.containsBeanDefinition(BeanIds.MESSAGE_BROKER)) {
        return beanFactory.getBeanDefinition(BeanIds.MESSAGE_BROKER);
    } else {//from w  w  w.j  a va  2 s . co m
        for (String beanDefName : beanFactory.getBeanDefinitionNames()) {
            BeanDefinition beanDef = beanFactory.getBeanDefinition(beanDefName);
            if (beanDef.getBeanClassName().equals(MESSAGE_BROKER_FACTORY_BEAN_CLASS_NAME)) {
                return beanDef;
            }
        }
    }
    return null;
}

From source file:org.springframework.flex.config.RemotingAnnotationPostProcessor.java

/**
 * Helper that searches the BeanFactory for beans annotated with @RemotingDestination, being careful not to force
 * eager creation of the beans if it can be avoided.
 * /*  w  w w .ja  v  a  2  s  .  c  om*/
 * @param beanFactory the BeanFactory to search
 * @return a set of collected RemotingDestinationMetadata
 */
private Set<RemotingDestinationMetadata> findRemotingDestinations(ConfigurableListableBeanFactory beanFactory) {
    Set<RemotingDestinationMetadata> remotingDestinations = new HashSet<RemotingDestinationMetadata>();
    Set<String> beanNames = new HashSet<String>();
    beanNames.addAll(Arrays.asList(beanFactory.getBeanDefinitionNames()));
    if (beanFactory.getParentBeanFactory() instanceof ListableBeanFactory) {
        beanNames.addAll(Arrays
                .asList(((ListableBeanFactory) beanFactory.getParentBeanFactory()).getBeanDefinitionNames()));
    }
    for (String beanName : beanNames) {
        if (beanName.startsWith("scopedTarget.")) {
            continue;
        }
        RemotingDestination remotingDestination = null;
        BeanDefinition bd = beanFactory.getMergedBeanDefinition(beanName);
        if (bd.isAbstract() || bd.isLazyInit()) {
            continue;
        }
        if (bd instanceof AbstractBeanDefinition) {
            AbstractBeanDefinition abd = (AbstractBeanDefinition) bd;
            if (abd.hasBeanClass()) {
                Class<?> beanClass = abd.getBeanClass();
                remotingDestination = AnnotationUtils.findAnnotation(beanClass, RemotingDestination.class);
                if (remotingDestination != null) {
                    remotingDestinations
                            .add(new RemotingDestinationMetadata(remotingDestination, beanName, beanClass));
                    continue;
                }
            }
        }
        Class<?> handlerType = beanFactory.getType(beanName);
        if (handlerType != null) {
            remotingDestination = AnnotationUtils.findAnnotation(handlerType, RemotingDestination.class);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Could not get type of bean '" + beanName + "' from bean factory.");
            }
        }
        if (remotingDestination != null) {
            remotingDestinations
                    .add(new RemotingDestinationMetadata(remotingDestination, beanName, handlerType));
        }
    }
    return remotingDestinations;
}

From source file:org.springframework.richclient.application.ProgressMonitoringBeanFactoryPostProcessor.java

/**
 * Notifies this instance's associated progress monitor of progress made
 * while processing the given bean factory.
 * // w  w  w. ja  va  2 s  .co  m
 * @param beanFactory the bean factory that is to be processed.
 */
public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) throws BeansException {

    if (beanFactory == null) {
        return;
    }

    String[] beanNames = beanFactory.getBeanDefinitionNames();
    int singletonBeanCount = 0;

    for (int i = 0; i < beanNames.length; i++) {
        // using beanDefinition to check singleton property because when
        // accessing through
        // context (applicationContext.isSingleton(beanName)), bean will be
        // created already,
        // possibly bypassing other BeanFactoryPostProcessors
        BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanNames[i]);

        if (beanDefinition.isSingleton()) {
            singletonBeanCount++;
        }

    }

    this.progressMonitor.taskStarted(this.loadingAppContextMessage, singletonBeanCount);

    beanFactory.addBeanPostProcessor(new ProgressMonitoringBeanPostProcessor(beanFactory));

}