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

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

Introduction

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

Prototype

BeanDefinition getMergedBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;

Source Link

Document

Return a merged BeanDefinition for the given bean name, merging a child bean definition with its parent if necessary.

Usage

From source file:me.springframework.di.spring.SpringConfigurationLoader.java

/**
 * Returns a {@link Map} of {@link MutableInstance MutableInstances},
 * indexed by name.//from w  w w  .j a  v a  2s  .co m
 * 
 * @param registry
 *            The {@link BeanDefinitionRegistry} holding the bean
 *            definitions.
 * @return A {@link Map} of {@link MutableInstance MutableInstances}
 *         representing the root beans defined by the
 *         {@link ListableBeanFactory}.
 */
protected static MutableContext loadBeans(ConfigurableListableBeanFactory factory) {
    MutableContext context = new MutableContext();
    for (String name : factory.getBeanDefinitionNames()) {
        for (String alias : factory.getAliases(name)) {
            context.addAlias(alias, name);
        }
    }

    for (String name : factory.getBeanDefinitionNames()) {
        BeanDefinition definition = factory.getBeanDefinition(name);
        if (!definition.isAbstract()) {
            BeanDefinition merged = factory.getMergedBeanDefinition(name);
            MutableInstance instance = new MutableInstance(name);
            load(instance, merged, context);
            context.addInstance(name, instance);
        }
    }
    return context;
}

From source file:org.brekka.stillingar.spring.pc.PropertyDefChangeListener.java

/**
 * Update the property with the new value
 *//*w w w.  j  a v a2s.  c o m*/
@Override
public void onChange(String newValue) {
    ConfigurableListableBeanFactory beanFactory = beanFactoryRef.get();
    if (beanFactory == null) {
        return;
    }
    BeanDefinition beanDef = beanFactory.getMergedBeanDefinition(beanName);
    MutablePropertyValues mutablePropertyValues = beanDef.getPropertyValues();
    PropertyValue propertyValue = mutablePropertyValues.getPropertyValue(propertyName);
    if (!ObjectUtils.nullSafeEquals(newValue, propertyValue.getValue())) {
        mutablePropertyValues.add(propertyValue.getName(), newValue);
    }
}

From source file:org.brekka.stillingar.spring.pc.ConstructorArgDefChangeListener.java

@Override
protected void onChange(String newValue) {
    ConfigurableListableBeanFactory beanFactory = beanFactoryRef.get();
    if (beanFactory == null) {
        return;//from www.j  a va 2  s .  c o m
    }

    BeanDefinition beanDef = beanFactory.getMergedBeanDefinition(beanName);
    ConstructorArgumentValues mutableConstructorValues = beanDef.getConstructorArgumentValues();
    ValueHolder valueHolder = null;
    List<ValueHolder> genericArgumentValues = mutableConstructorValues.getGenericArgumentValues();
    if (constructorArgIndex != null) {
        valueHolder = mutableConstructorValues.getIndexedArgumentValues().get(constructorArgIndex);
        if (valueHolder == null) {
            throw new IllegalStateException(
                    String.format("Failed to find constructor arg at index %d", constructorArgIndex));
        }
    } else if (genericArgumentValues.size() == 1) {
        valueHolder = genericArgumentValues.get(0);
    } else {
        for (ValueHolder vh : genericArgumentValues) {
            if (vh.getType().equals(constructorArgType)) {
                valueHolder = vh;
            }
        }
        if (valueHolder == null) {
            throw new IllegalStateException(
                    String.format("Failed to find constructor arg with type '%s'", constructorArgType));
        }
    }
    if (!ObjectUtils.nullSafeEquals(newValue, valueHolder.getValue())) {
        valueHolder.setValue(newValue);
        try {
            /*
             * Spring implements caching of constructor values, which can be reset by clearing the package-private
             * field 'resolvedConstructorOrFactoryMethod' on RootBeanDefinition. Naturally this will fail if a
             * security manager is present but there doesn't seem to be any other way to do it. Make sure to warn
             * about this in the documentation!
             */
            Field field = beanDef.getClass().getDeclaredField("resolvedConstructorOrFactoryMethod");
            field.setAccessible(true);
            field.set(beanDef, null);
        } catch (Exception e) {
            throw new ConfigurationException(String.format(
                    "Unable to update value for constructor argument '%s'. "
                            + "Failed to reset the cached constructor state for bean '%s'",
                    (constructorArgIndex != null ? constructorArgIndex.toString() : constructorArgType),
                    beanName), e);
        }
    }
}

From source file:org.nuunframework.spring.SpringModule.java

@SuppressWarnings("unchecked")
private void bindFromApplicationContext() {
    boolean debugEnabled = logger.isDebugEnabled();

    ConfigurableListableBeanFactory currentBeanFactory = this.beanFactory;
    do {//from w  ww.jav a  2 s .c  o m
        for (String beanName : currentBeanFactory.getBeanDefinitionNames()) {
            BeanDefinition beanDefinition = currentBeanFactory.getMergedBeanDefinition(beanName);
            if (!beanDefinition.isAbstract()) {
                Class<?> beanClass = classFromString(beanDefinition.getBeanClassName());
                if (beanClass == null) {
                    logger.warn("Cannot bind spring bean " + beanName + " because its class "
                            + beanDefinition.getBeanClassName() + " failed to load");
                    return;
                }

                SpringBeanDefinition springBeanDefinition = new SpringBeanDefinition(beanName,
                        currentBeanFactory);

                // Adding bean with its base type
                addBeanDefinition(beanClass, springBeanDefinition);

                // Adding bean with its parent type if enabled
                Class<?> parentClass = beanClass.getSuperclass();
                if (parentClass != null && parentClass != Object.class)
                    addBeanDefinition(parentClass, springBeanDefinition);

                // Adding bean with its immediate interfaces if enabled
                for (Class<?> i : beanClass.getInterfaces())
                    addBeanDefinition(i, springBeanDefinition);
            }
        }
        BeanFactory factory = currentBeanFactory.getParentBeanFactory();
        if (factory != null) {
            if (factory instanceof ConfigurableListableBeanFactory)
                currentBeanFactory = (ConfigurableListableBeanFactory) factory;
            else {
                logger.info(
                        "Cannot go up further in the bean factory hierarchy, parent bean factory doesn't implement ConfigurableListableBeanFactory");
                currentBeanFactory = null;
            }
        } else
            currentBeanFactory = null;
    } while (currentBeanFactory != null);

    for (Map.Entry<Class<?>, Map<String, SpringBeanDefinition>> entry : this.beanDefinitions.entrySet()) {
        Class<?> type = entry.getKey();
        Map<String, SpringBeanDefinition> definitions = entry.getValue();

        // Bind by name for each bean of this type and by type if there is no ambiguity
        for (SpringBeanDefinition candidate : definitions.values()) {
            if (debugEnabled)
                logger.info("Binding spring bean " + candidate.getName() + " by name and type "
                        + type.getCanonicalName());

            bind(type).annotatedWith(Names.named(candidate.getName())).toProvider(
                    new ByNameSpringContextProvider(type, candidate.getName(), candidate.getBeanFactory()));
        }
    }
}

From source file:io.nuun.plugin.spring.SpringModule.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void bindFromApplicationContext() {
    boolean debugEnabled = logger.isDebugEnabled();

    ConfigurableListableBeanFactory currentBeanFactory = beanFactory;
    do {/*from   w w w  .  j  a  v a  2s  . c om*/
        for (String beanName : currentBeanFactory.getBeanDefinitionNames()) {
            BeanDefinition beanDefinition = currentBeanFactory.getMergedBeanDefinition(beanName);
            if (!beanDefinition.isAbstract()) {
                Class<?> beanClass = classFromString(beanDefinition.getBeanClassName());
                if (beanClass == null) {
                    logger.warn("Cannot bind spring bean " + beanName + " because its class "
                            + beanDefinition.getBeanClassName() + " failed to load");
                    return;
                }

                SpringBeanDefinition springBeanDefinition = new SpringBeanDefinition(beanName,
                        currentBeanFactory);

                // Adding bean with its base type
                addBeanDefinition(beanClass, springBeanDefinition);

                // Adding bean with its parent type if enabled
                Class<?> parentClass = beanClass.getSuperclass();
                if (parentClass != null && parentClass != Object.class) {
                    addBeanDefinition(parentClass, springBeanDefinition);
                }

                // Adding bean with its immediate interfaces if enabled
                for (Class<?> i : beanClass.getInterfaces()) {
                    addBeanDefinition(i, springBeanDefinition);
                }
            }
        }
        BeanFactory factory = currentBeanFactory.getParentBeanFactory();
        if (factory != null) {
            if (factory instanceof ConfigurableListableBeanFactory) {
                currentBeanFactory = (ConfigurableListableBeanFactory) factory;
            } else {
                logger.info(
                        "Cannot go up further in the bean factory hierarchy, parent bean factory doesn't implement ConfigurableListableBeanFactory");
                currentBeanFactory = null;
            }
        } else {
            currentBeanFactory = null;
        }
    } while (currentBeanFactory != null);

    for (Map.Entry<Class<?>, Map<String, SpringBeanDefinition>> entry : beanDefinitions.entrySet()) {
        Class<?> type = entry.getKey();
        Map<String, SpringBeanDefinition> definitions = entry.getValue();

        // Bind by name for each bean of this type and by type if there is no ambiguity
        for (SpringBeanDefinition candidate : definitions.values()) {
            if (debugEnabled) {
                logger.info("Binding spring bean " + candidate.getName() + " by name and type "
                        + type.getCanonicalName());
            }

            bind(type).annotatedWith(Names.named(candidate.getName())).toProvider(
                    new ByNameSpringContextProvider(type, candidate.getName(), candidate.getBeanFactory()));
        }
    }
}

From source file:org.seedstack.spring.internal.SpringModule.java

@SuppressWarnings("unchecked")
private void bindFromApplicationContext() {
    boolean debugEnabled = LOGGER.isDebugEnabled();

    ConfigurableListableBeanFactory currentBeanFactory = this.beanFactory;
    do {/*from   w  w  w .  j a  v a  2s  .co  m*/
        for (String beanName : currentBeanFactory.getBeanDefinitionNames()) {
            BeanDefinition beanDefinition = currentBeanFactory.getMergedBeanDefinition(beanName);
            if (!beanDefinition.isAbstract()) {
                Class<?> beanClass;
                try {
                    beanClass = Class.forName(beanDefinition.getBeanClassName());
                } catch (ClassNotFoundException e) {
                    LOGGER.warn("Cannot bind spring bean " + beanName + " because its class "
                            + beanDefinition.getBeanClassName() + " failed to load", e);
                    continue;
                }

                // FactoryBean special case: retrieve it and query for the object type it creates
                if (FactoryBean.class.isAssignableFrom(beanClass)) {
                    beanClass = ((FactoryBean) currentBeanFactory.getBean('&' + beanName)).getObjectType();
                    if (beanClass == null) {
                        LOGGER.warn("Cannot bind spring bean " + beanName
                                + " because its factory bean cannot determine its class");
                        continue;
                    }
                }

                SpringBeanDefinition springBeanDefinition = new SpringBeanDefinition(beanName,
                        currentBeanFactory);

                // Adding bean with its base type
                addBeanDefinition(beanClass, springBeanDefinition);

                // Adding bean with its parent type if enabled
                Class<?> parentClass = beanClass.getSuperclass();
                if (parentClass != null && parentClass != Object.class) {
                    addBeanDefinition(parentClass, springBeanDefinition);
                }

                // Adding bean with its immediate interfaces if enabled
                for (Class<?> i : beanClass.getInterfaces()) {
                    addBeanDefinition(i, springBeanDefinition);
                }
            }
        }
        BeanFactory factory = currentBeanFactory.getParentBeanFactory();
        if (factory != null) {
            if (factory instanceof ConfigurableListableBeanFactory) {
                currentBeanFactory = (ConfigurableListableBeanFactory) factory;
            } else {
                LOGGER.info(
                        "Cannot go up further in the bean factory hierarchy, parent bean factory doesn't implement ConfigurableListableBeanFactory");
                currentBeanFactory = null;
            }
        } else {
            currentBeanFactory = null;
        }
    } while (currentBeanFactory != null);

    for (Map.Entry<Class<?>, Map<String, SpringBeanDefinition>> entry : this.beanDefinitions.entrySet()) {
        Class<?> type = entry.getKey();
        Map<String, SpringBeanDefinition> definitions = entry.getValue();

        // Bind by name for each bean of this type and by type if there is no ambiguity
        for (SpringBeanDefinition candidate : definitions.values()) {
            if (debugEnabled) {
                LOGGER.info("Binding spring bean " + candidate.getName() + " by name and type "
                        + type.getCanonicalName());
            }

            bind(type).annotatedWith(Names.named(candidate.getName()))
                    .toProvider(new SpringBeanProvider(type, candidate.getName(), candidate.getBeanFactory()));
        }
    }
}

From source file:org.kuali.rice.krad.datadictionary.uif.UifBeanFactoryPostProcessor.java

@SuppressWarnings("unchecked")
protected void visitList(String nestedPropertyName, String propertyName, BeanDefinition beanDefinition,
        Map<String, String> parentExpressionGraph, Map<String, String> expressionGraph, List listVal,
        ConfigurableListableBeanFactory beanFactory, Set<String> processedBeanNames) {
    boolean isMergeEnabled = false;
    if (listVal instanceof ManagedList) {
        isMergeEnabled = ((ManagedList) listVal).isMergeEnabled();
    }//from   w w  w.j av a  2 s  .  c om

    ManagedList newList = new ManagedList();
    newList.setMergeEnabled(isMergeEnabled);

    // if merging, need to find size of parent list so we can know which element to set
    // when evaluating expressions
    int parentListSize = 0;
    if (isMergeEnabled && StringUtils.isNotBlank(beanDefinition.getParentName())) {
        BeanDefinition parentBeanDefinition = beanFactory
                .getMergedBeanDefinition(beanDefinition.getParentName());
        PropertyValue parentListPropertyValue = parentBeanDefinition.getPropertyValues()
                .getPropertyValue(propertyName);
        if (parentListPropertyValue != null) {
            List parentList = (List) parentListPropertyValue.getValue();
            parentListSize = parentList.size();
        }
    }

    for (int i = 0; i < listVal.size(); i++) {
        Object elem = listVal.get(i);

        int elementPosition = i + parentListSize;
        String elemPropertyName = nestedPropertyName + "[" + elementPosition + "]";

        if (hasExpression(elem)) {
            String strValue = getStringValue(elem);

            expressionGraph.put(elemPropertyName, strValue);
            newList.add(i, null);
        } else {
            // process list value bean definition as a top level bean
            if ((elem instanceof BeanDefinition) || (elem instanceof BeanDefinitionHolder)) {
                String beanName = null;
                BeanDefinition beanDefinitionValue;
                if (elem instanceof BeanDefinition) {
                    beanDefinitionValue = (BeanDefinition) elem;
                } else {
                    beanDefinitionValue = ((BeanDefinitionHolder) elem).getBeanDefinition();
                    beanName = ((BeanDefinitionHolder) elem).getBeanName();
                }

                processBeanDefinition(beanName, beanDefinitionValue, beanFactory, processedBeanNames);
            }

            newList.add(i, elem);
        }
    }

    // determine if we need to clear any parent expressions for this list
    if (!isMergeEnabled) {
        // clear any expressions that match the property name minus index
        Map<String, String> adjustedParentExpressionGraph = new HashMap<String, String>();
        for (Map.Entry<String, String> parentExpression : parentExpressionGraph.entrySet()) {
            if (!parentExpression.getKey().startsWith(nestedPropertyName + "[")) {
                adjustedParentExpressionGraph.put(parentExpression.getKey(), parentExpression.getValue());
            }
        }

        parentExpressionGraph.clear();
        parentExpressionGraph.putAll(adjustedParentExpressionGraph);
    }

    listVal.clear();
    listVal.addAll(newList);
}

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

private boolean isAmfConversionServiceProcessorConfigured(ConfigurableListableBeanFactory beanFactory,
        ManagedSet<RuntimeBeanReference> configProcessors) {

    for (RuntimeBeanReference configProcessor : configProcessors) {
        BeanDefinition bd = beanFactory.getMergedBeanDefinition(configProcessor.getBeanName());
        if (bd instanceof AbstractBeanDefinition) {
            AbstractBeanDefinition abd = (AbstractBeanDefinition) bd;
            if (!abd.hasBeanClass()) {
                try {
                    abd.resolveBeanClass(beanFactory.getBeanClassLoader());
                } catch (ClassNotFoundException ex) {
                    throw new CannotLoadBeanClassException(abd.getResourceDescription(),
                            configProcessor.getBeanName(), abd.getBeanClassName(), ex);
                }// w ww. j  a v a  2  s . com
            }
            if (AbstractAmfConversionServiceConfigProcessor.class.isAssignableFrom(abd.getBeanClass())) {
                return true;
            }
        }
    }
    return false;
}

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.
 * /*from  ww  w. j  a v  a2  s .c o m*/
 * @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.integration.config.xml.GatewayParserTests.java

@Test
public void testFactoryBeanObjectTypeWithServiceInterface() throws Exception {
    ConfigurableListableBeanFactory beanFactory = ((GenericApplicationContext) context).getBeanFactory();
    Object attribute = beanFactory.getMergedBeanDefinition("&oneWay")
            .getAttribute(IntegrationConfigUtils.FACTORY_BEAN_OBJECT_TYPE);
    assertEquals(TestService.class.getName(), attribute);
}