BeanDefinition相关类

1.1 BeanDefinition类图:

BeanDefinition描述了一个bean的实例,包括属性值,构造方法参数值和继承自它的类的更多信息。BeanDefinition仅仅是一个最简单的接口,一下为BeanDefinition的类图
这里写图片描述
这个接口描述bean的结构,对应XML中的< bean >或者配置类中的@Bean进行封装。
最顶层继承自BeanMetadataElement和AttributeAccessor接口。

1.1.1 AbstractBeanDefinition

主要操作对象属性:

package org.springframework.beans.factory.support;

import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.BeanMetadataAttributeAccessor;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.core.io.DescriptiveResource;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

@SuppressWarnings("serial")
public abstract class AbstractBeanDefinition extends BeanMetadataAttributeAccessor
        implements BeanDefinition, Cloneable {
    public static final String SCOPE_DEFAULT = "";
    /***************************自动注入时的策略***************************/
    public static final int AUTOWIRE_NO = AutowireCapableBeanFactory.AUTOWIRE_NO;
    public static final int AUTOWIRE_BY_NAME = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME;
    public static final int AUTOWIRE_BY_TYPE = AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE;
    public static final int AUTOWIRE_CONSTRUCTOR = AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR;
    @Deprecated
    public static final int AUTOWIRE_AUTODETECT = AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT;
    /***************************依赖检查的策略***************************/
    //不做检查
    public static final int DEPENDENCY_CHECK_NONE = 0;
    //检查除简单类型属性以及集合类型属性外的引用类型属性
    public static final int DEPENDENCY_CHECK_OBJECTS = 1;
    //检查简单类型属性以及集合类型属性
    public static final int DEPENDENCY_CHECK_SIMPLE = 2;
    //全部检查
    public static final int DEPENDENCY_CHECK_ALL = 3;
    public static final String INFER_METHOD = "(inferred)";
    //表示这个Bean的类,可能是字符串,比如"com.insaneXs.TestA",也可能是class对象
    private volatile Object beanClass;
    //表示这个bean的范围
    private String scope = SCOPE_DEFAULT;
    //是否是抽象的,在定义bean的时候,由abstract属性设置,抽象的BeanDefition在getBean时会抛出异常
    private boolean abstractFlag = false;
    //是否延迟加载
    private boolean lazyInit = false;
    private int autowireMode = AUTOWIRE_NO;
    private int dependencyCheck = DEPENDENCY_CHECK_NONE;
    //依赖关系,在定义bean的时候,由depend-on属性设置,被依赖的bean在该bean之前被容器初始化
    private String[] dependsOn;
    private boolean autowireCandidate = true;
    private boolean primary = false;
    private final Map<String, AutowireCandidateQualifier> qualifiers =
            new LinkedHashMap<String, AutowireCandidateQualifier>(0);
    //是都允许访问非共有的属性
    private boolean nonPublicAccessAllowed = true;
    //调用构造函数时,是否采用宽松匹配
    private boolean lenientConstructorResolution = true;
    //工厂类Bean的名字
    private String factoryBeanName;
    //工厂方法的名字
    private String factoryMethodName;
    //构造函数参数的封装,看下文ConstructorArgumentValues
    private ConstructorArgumentValues constructorArgumentValues;
    //在定义bean时,property标签设置的属性
    private MutablePropertyValues propertyValues;
    //跟Bean定义时的look-up有关
    private MethodOverrides methodOverrides = new MethodOverrides();
    //指定init方法名称,会在初始化的时候被调用
    private String initMethodName;
    //指定destroy方法名称,会在被销毁时调用
    private String destroyMethodName;
    private boolean enforceInitMethod = true;
    private boolean enforceDestroyMethod = true;
    //表示该Bean是否是由程序生成的
    private boolean synthetic = false;
    private int role = BeanDefinition.ROLE_APPLICATION;
    private String description;
    // 如果设置了@Scope(proxyMode=ScopedProxyMode.TARGET_CLASS)则会将resource设置为BeanDefinitionResource
    private Resource resource;
protected AbstractBeanDefinition() {
        this(null, null);
    }

    // 构造方法
    protected AbstractBeanDefinition() {
        this(null, null);
    }

    // 构造方法
    protected AbstractBeanDefinition(ConstructorArgumentValues cargs, MutablePropertyValues pvs) {
        setConstructorArgumentValues(cargs);
        setPropertyValues(pvs);
    }

    // 构造方法
    protected AbstractBeanDefinition(BeanDefinition original) {
        setParentName(original.getParentName());
        setBeanClassName(original.getBeanClassName());
        setScope(original.getScope());
        setAbstract(original.isAbstract());
        setLazyInit(original.isLazyInit());
        setFactoryBeanName(original.getFactoryBeanName());
        setFactoryMethodName(original.getFactoryMethodName());
        setConstructorArgumentValues(new ConstructorArgumentValues(original.getConstructorArgumentValues()));
        setPropertyValues(new MutablePropertyValues(original.getPropertyValues()));
        setRole(original.getRole());
        setSource(original.getSource());
        copyAttributesFrom(original);

        if (original instanceof AbstractBeanDefinition) {
            AbstractBeanDefinition originalAbd = (AbstractBeanDefinition) original;
            if (originalAbd.hasBeanClass()) {
                setBeanClass(originalAbd.getBeanClass());
            }
            setAutowireMode(originalAbd.getAutowireMode());
            setDependencyCheck(originalAbd.getDependencyCheck());
            setDependsOn(originalAbd.getDependsOn());
            setAutowireCandidate(originalAbd.isAutowireCandidate());
            setPrimary(originalAbd.isPrimary());
            copyQualifiersFrom(originalAbd);
            setNonPublicAccessAllowed(originalAbd.isNonPublicAccessAllowed());
            setLenientConstructorResolution(originalAbd.isLenientConstructorResolution());
            setMethodOverrides(new MethodOverrides(originalAbd.getMethodOverrides()));
            setInitMethodName(originalAbd.getInitMethodName());
            setEnforceInitMethod(originalAbd.isEnforceInitMethod());
            setDestroyMethodName(originalAbd.getDestroyMethodName());
            setEnforceDestroyMethod(originalAbd.isEnforceDestroyMethod());
            setSynthetic(originalAbd.isSynthetic());
            setResource(originalAbd.getResource());
        }
        else {
            setResourceDescription(original.getResourceDescription());
        }
    }
}

ConstructorArgumentValues :构造参数,保存了构造方法所有的参数值,它不仅支持类型匹配的普通参数,也支持根据参数列表中的索引位置来提供参数。提供了两个变量来保存参数:带索引的和不带索引的

public class ConstructorArgumentValues {
    private final Map<Integer, ValueHolder> indexedArgumentValues = new LinkedHashMap<Integer, ValueHolder>(0);
    private final List<ValueHolder> genericArgumentValues = new LinkedList<ValueHolder>();
}

MutablePropertyValues:对象属性

public class MutablePropertyValues implements PropertyValues, Serializable {
    private final List<PropertyValue> propertyValueList;// 属性,PropertyValue类似map
    private Set<String> processedProperties;
    private volatile boolean converted = false;
}

resource:属性

定义一个类,增加@Scope(proxyMode=ScopedProxyMode.TARGET_CLASS)注解,Scope注解中属性proxyMode作用

@Component
@Scope(proxyMode=ScopedProxyMode.TARGET_CLASS)
public class SpringBeanTest2 {

    public SpringBeanTest2() {
        System.out.println("【SpringBeanTest2】 构造");
    }
}
public class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateComponentProvider {
    protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
            Assert.notEmpty(basePackages, "At least one base package must be specified");
            Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>();
            for (String basePackage : basePackages) {
                Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
                for (BeanDefinition candidate : candidates) {
                    ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
                    candidate.setScope(scopeMetadata.getScopeName());
                    String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
                    if (candidate instanceof AbstractBeanDefinition) {
                        postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
                    }
                    if (candidate instanceof AnnotatedBeanDefinition) {
                        AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
                    }
                    if (checkCandidate(beanName, candidate)) {
                        BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
                        // 判断是否需要代理,需要则返回代理对象,否则返回原对象
                        definitionHolder =
                                AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
                        beanDefinitions.add(definitionHolder);
                        registerBeanDefinition(definitionHolder, this.registry);
                    }
                }
            }
            return beanDefinitions;
        }
}
public abstract class ScopedProxyUtils {
    public static BeanDefinitionHolder createScopedProxy(BeanDefinitionHolder definition,
                BeanDefinitionRegistry registry, boolean proxyTargetClass) {

            // 得到原对象BeanDefintion名字
            String originalBeanName = definition.getBeanName();
            BeanDefinition targetDefinition = definition.getBeanDefinition();
            // 重新命名scopedTarget.【originalBeanName 】
            String targetBeanName = getTargetBeanName(originalBeanName);


            RootBeanDefinition proxyDefinition = new RootBeanDefinition(ScopedProxyFactoryBean.class);
            proxyDefinition.setDecoratedDefinition(new BeanDefinitionHolder(targetDefinition, targetBeanName));
            proxyDefinition.setOriginatingBeanDefinition(targetDefinition);
            proxyDefinition.setSource(definition.getSource());
            proxyDefinition.setRole(targetDefinition.getRole());

            proxyDefinition.getPropertyValues().add("targetBeanName", targetBeanName);
            if (proxyTargetClass) {
                targetDefinition.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
                // ScopedProxyFactoryBean's "proxyTargetClass" default is TRUE, so we don't need to set it explicitly here.
            }
            else {
                proxyDefinition.getPropertyValues().add("proxyTargetClass", Boolean.FALSE);
            }

            // Copy autowire settings from original bean definition.
            proxyDefinition.setAutowireCandidate(targetDefinition.isAutowireCandidate());
            proxyDefinition.setPrimary(targetDefinition.isPrimary());
            if (targetDefinition instanceof AbstractBeanDefinition) {
                proxyDefinition.copyQualifiersFrom((AbstractBeanDefinition) targetDefinition);
            }

            // The target bean should be ignored in favor of the scoped proxy.
            targetDefinition.setAutowireCandidate(false);
            targetDefinition.setPrimary(false);
            // 注册原对象
            registry.registerBeanDefinition(targetBeanName, targetDefinition);
            // 返回代理对象
            return new BeanDefinitionHolder(proxyDefinition, originalBeanName, definition.getAliases());
        }
}

代理前:
用ScannedGenericBeanDefinition定义的source,resource会赋值为文件路径,其他BeanDefinition则为空,
这里写图片描述
代理后
resource变成先前的BeanDefinition,并且先前的BeanDefinitioin会变成scopeTarget.springBeanTest2,将代理的重新命名为该springBeanTest2
这里写图片描述
这里写图片描述

1.1.2 ChildBeanDefinition

可以继承父类,对RootBeanDefinition有一定的依赖关系
如XML配置:
加载id=“sunBean”会用ChildBeanDefinition创建

<beans>
<bean id="parentBean">
    <property name="name"><value>parent</value></property>
    <property name="age"><value>1</value></property>
</bean>
<bean id="sunBean" class="SunBean"
      parent="parentBean" init-method="initialize">
    <property name="name"><value>override</value></property>
</bean>

1.1.3 RootBeanDefinition

1.1.4 GenericBeanDefinition

1.1.5 ScannedGenericBeanDefinition

// 构造方法
public ScannedGenericBeanDefinition(MetadataReader metadataReader) {
        Assert.notNull(metadataReader, "MetadataReader must not be null");
        this.metadata = metadataReader.getAnnotationMetadata();
        setBeanClassName(this.metadata.getClassName());
    }

扫描注入的属性,@ComponentScan或者使用ClassPathScanningCandidateComponentProvider扫描的类

1.1.6 AnnotatedGenericBeanDefinition

代表一个从配置源(XML,Java Config等)中生成的BeanDefinition

2.1 BeanDefinitionHolder

3.1 BeanDefinitionRegistry

4.1 BeanDefinitionReader

5.1 ClassPathBeanDefinitionScanner

这里写图片描述

5.1.1 ClassPathScanningCandidateComponentProvider

public static void main(String[] args) {
        ClassPathScanningCandidateComponentProvider cps = new ClassPathScanningCandidateComponentProvider(true);
        // 定义包含属性
        TypeFilter myTypeFilter = new AnnotationTypeFilter(MyComponent.class);
        cps.addIncludeFilter(myTypeFilter);
        // 搜索包
        Set<BeanDefinition> beanDefinitions = cps.findCandidateComponents("com.gz.spring.springbean");
    }

5.1.2 ClassPathBeanDefinitionScanner

6.1 Spring中Utils

6.1.1 BeanDefinitionReaderUtils


   //  ⑴
   // 注册post processors相关的类,如在创建
   // AnnotationConfigApplicationContext对象是会创建
   // AnnotatedBeanDefinitionReader对象,
   // 这是会调用注册post processors相关的类
    public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) 

    // ⑵ 初始化AnnotatedBeanDefinition默认注解属性
    public static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd) 

    // ⑶ 创建一个代理bean,如创建BeanDefinitioin会检查Scoper是否ScopeProxyMode,
    // 如@Scope(value=WebApplicationContext.SCOPE_SESSION,
    // proxyMode=ScopedProxyMode.INTERFACES)
    // proxyMode = NO 为不代理,否则代理,
    // 主要作用请看(https://www.jianshu.com/p/fcdcbaace675)文章

    static BeanDefinitionHolder applyScopedProxyMode(
            ScopeMetadata metadata, BeanDefinitionHolder definition, BeanDefinitionRegistry registry) 

6.1.2 BeanDefinitionReaderUtils

// 创建GenericBeanDefinition
public static AbstractBeanDefinition createBeanDefinition

// 生成一个BeanFactory全局唯一的Bean的名字
public static String generateBeanName(BeanDefinition beanDefinition, BeanDefinitionRegistry registry)
public static String generateBeanName(
            BeanDefinition definition, BeanDefinitionRegistry registry, boolean isInnerBean)

// 注册BeanDefinition
public static void registerBeanDefinition(
            BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)

// 注册BeanDefinition,这个是利用generateBeanName得到的BeanDefinition的Name
public static String registerWithGeneratedName(
            AbstractBeanDefinition definition, BeanDefinitionRegistry registry)
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页