Search in sources :

Example 11 with BeanDefinition

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

the class AbstractAutowireCapableBeanFactory method applyBeanPropertyValues.

@Override
public void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException {
    markBeanAsCreated(beanName);
    BeanDefinition bd = getMergedBeanDefinition(beanName);
    BeanWrapper bw = new BeanWrapperImpl(existingBean);
    initBeanWrapper(bw);
    applyPropertyValues(beanName, bd, bw, bd.getPropertyValues());
}
Also used : BeanWrapper(org.springframework.beans.BeanWrapper) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition)

Example 12 with BeanDefinition

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

the class RequiredAnnotationBeanPostProcessor method shouldSkip.

/**
	 * Check whether the given bean definition is not subject to the annotation-based
	 * required property check as performed by this post-processor.
	 * <p>The default implementations check for the presence of the
	 * {@link #SKIP_REQUIRED_CHECK_ATTRIBUTE} attribute in the bean definition, if any.
	 * It also suggests skipping in case of a bean definition with a "factory-bean"
	 * reference set, assuming that instance-based factories pre-populate the bean.
	 * @param beanFactory the BeanFactory to check against
	 * @param beanName the name of the bean to check against
	 * @return {@code true} to skip the bean; {@code false} to process it
	 */
protected boolean shouldSkip(ConfigurableListableBeanFactory beanFactory, String beanName) {
    if (beanFactory == null || !beanFactory.containsBeanDefinition(beanName)) {
        return false;
    }
    BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
    if (beanDefinition.getFactoryBeanName() != null) {
        return true;
    }
    Object value = beanDefinition.getAttribute(SKIP_REQUIRED_CHECK_ATTRIBUTE);
    return (value != null && (Boolean.TRUE.equals(value) || Boolean.valueOf(value.toString())));
}
Also used : RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition)

Example 13 with BeanDefinition

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

the class DefaultListableBeanFactoryTests method testScopeInheritanceForChildBeanDefinitions.

@Test
public void testScopeInheritanceForChildBeanDefinitions() throws Exception {
    RootBeanDefinition parent = new RootBeanDefinition();
    parent.setScope("bonanza!");
    AbstractBeanDefinition child = new ChildBeanDefinition("parent");
    child.setBeanClass(TestBean.class);
    DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
    factory.registerBeanDefinition("parent", parent);
    factory.registerBeanDefinition("child", child);
    BeanDefinition def = factory.getMergedBeanDefinition("child");
    assertEquals("Child 'scope' not inherited", "bonanza!", def.getScope());
}
Also used : AbstractBeanDefinition(org.springframework.beans.factory.support.AbstractBeanDefinition) DefaultListableBeanFactory(org.springframework.beans.factory.support.DefaultListableBeanFactory) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) ChildBeanDefinition(org.springframework.beans.factory.support.ChildBeanDefinition) AbstractBeanDefinition(org.springframework.beans.factory.support.AbstractBeanDefinition) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) ChildBeanDefinition(org.springframework.beans.factory.support.ChildBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) Test(org.junit.Test)

Example 14 with BeanDefinition

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

the class ConfigurationClassBeanDefinitionReader method loadBeanDefinitionsForBeanMethod.

/**
	 * Read the given {@link BeanMethod}, registering bean definitions
	 * with the BeanDefinitionRegistry based on its contents.
	 */
private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod) {
    ConfigurationClass configClass = beanMethod.getConfigurationClass();
    MethodMetadata metadata = beanMethod.getMetadata();
    String methodName = metadata.getMethodName();
    // Do we need to mark the bean as skipped by its condition?
    if (this.conditionEvaluator.shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN)) {
        configClass.skippedBeanMethods.add(methodName);
        return;
    }
    if (configClass.skippedBeanMethods.contains(methodName)) {
        return;
    }
    // Consider name and any aliases
    AnnotationAttributes bean = AnnotationConfigUtils.attributesFor(metadata, Bean.class);
    List<String> names = new ArrayList<>(Arrays.asList(bean.getStringArray("name")));
    String beanName = (names.size() > 0 ? names.remove(0) : methodName);
    // Register aliases even when overridden
    for (String alias : names) {
        this.registry.registerAlias(beanName, alias);
    }
    // Has this effectively been overridden before (e.g. via XML)?
    if (isOverriddenByExistingDefinition(beanMethod, beanName)) {
        return;
    }
    ConfigurationClassBeanDefinition beanDef = new ConfigurationClassBeanDefinition(configClass, metadata);
    beanDef.setResource(configClass.getResource());
    beanDef.setSource(this.sourceExtractor.extractSource(metadata, configClass.getResource()));
    if (metadata.isStatic()) {
        // static @Bean method
        beanDef.setBeanClassName(configClass.getMetadata().getClassName());
        beanDef.setFactoryMethodName(methodName);
    } else {
        // instance @Bean method
        beanDef.setFactoryBeanName(configClass.getBeanName());
        beanDef.setUniqueFactoryMethodName(methodName);
    }
    beanDef.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
    beanDef.setAttribute(RequiredAnnotationBeanPostProcessor.SKIP_REQUIRED_CHECK_ATTRIBUTE, Boolean.TRUE);
    AnnotationConfigUtils.processCommonDefinitionAnnotations(beanDef, metadata);
    Autowire autowire = bean.getEnum("autowire");
    if (autowire.isAutowire()) {
        beanDef.setAutowireMode(autowire.value());
    }
    String initMethodName = bean.getString("initMethod");
    if (StringUtils.hasText(initMethodName)) {
        beanDef.setInitMethodName(initMethodName);
    }
    String destroyMethodName = bean.getString("destroyMethod");
    if (destroyMethodName != null) {
        beanDef.setDestroyMethodName(destroyMethodName);
    }
    // Consider scoping
    ScopedProxyMode proxyMode = ScopedProxyMode.NO;
    AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(metadata, Scope.class);
    if (attributes != null) {
        beanDef.setScope(attributes.getString("value"));
        proxyMode = attributes.getEnum("proxyMode");
        if (proxyMode == ScopedProxyMode.DEFAULT) {
            proxyMode = ScopedProxyMode.NO;
        }
    }
    // Replace the original bean definition with the target one, if necessary
    BeanDefinition beanDefToRegister = beanDef;
    if (proxyMode != ScopedProxyMode.NO) {
        BeanDefinitionHolder proxyDef = ScopedProxyCreator.createScopedProxy(new BeanDefinitionHolder(beanDef, beanName), this.registry, proxyMode == ScopedProxyMode.TARGET_CLASS);
        beanDefToRegister = new ConfigurationClassBeanDefinition((RootBeanDefinition) proxyDef.getBeanDefinition(), configClass, metadata);
    }
    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Registering bean definition for @Bean method %s.%s()", configClass.getMetadata().getClassName(), beanName));
    }
    this.registry.registerBeanDefinition(beanName, beanDefToRegister);
}
Also used : AnnotationAttributes(org.springframework.core.annotation.AnnotationAttributes) BeanDefinitionHolder(org.springframework.beans.factory.config.BeanDefinitionHolder) ArrayList(java.util.ArrayList) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) MethodMetadata(org.springframework.core.type.MethodMetadata) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) AnnotatedBeanDefinition(org.springframework.beans.factory.annotation.AnnotatedBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) AnnotatedGenericBeanDefinition(org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition) Autowire(org.springframework.beans.factory.annotation.Autowire)

Example 15 with BeanDefinition

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

the class ConfigurationClassPostProcessor method enhanceConfigurationClasses.

/**
	 * 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
	 */
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);
            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);
        }
    }
}
Also used : AbstractBeanDefinition(org.springframework.beans.factory.support.AbstractBeanDefinition) BeanDefinitionStoreException(org.springframework.beans.factory.BeanDefinitionStoreException) AbstractBeanDefinition(org.springframework.beans.factory.support.AbstractBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap)

Aggregations

BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)593 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)188 BeanDefinitionBuilder (org.springframework.beans.factory.support.BeanDefinitionBuilder)117 Test (org.junit.jupiter.api.Test)105 AbstractBeanDefinition (org.springframework.beans.factory.support.AbstractBeanDefinition)89 Element (org.w3c.dom.Element)73 Test (org.junit.Test)70 RuntimeBeanReference (org.springframework.beans.factory.config.RuntimeBeanReference)60 BeanComponentDefinition (org.springframework.beans.factory.parsing.BeanComponentDefinition)54 ManagedList (org.springframework.beans.factory.support.ManagedList)40 ClassPathScanningCandidateComponentProvider (org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider)39 AnnotatedBeanDefinition (org.springframework.beans.factory.annotation.AnnotatedBeanDefinition)36 BeanMetadataElement (org.springframework.beans.BeanMetadataElement)35 MutablePropertyValues (org.springframework.beans.MutablePropertyValues)33 BeanDefinitionRegistry (org.springframework.beans.factory.support.BeanDefinitionRegistry)33 BeanDefinitionHolder (org.springframework.beans.factory.config.BeanDefinitionHolder)30 AnnotationTypeFilter (org.springframework.core.type.filter.AnnotationTypeFilter)29 ArrayList (java.util.ArrayList)28 Method (java.lang.reflect.Method)27 GenericBeanDefinition (org.springframework.beans.factory.support.GenericBeanDefinition)27