0%

Spring源码学习-AbstractBeanDefinition

前言:Spring源码学习-AbstractBeanDefinition

简介

AbstractBeanDefinition继承了BeanMetadataAttributeAccessor类,实现了BeanDefinition与Cloneable接口,类图如下

image-20200102000658264

AbstractBeanDefinition中定义了很多bean的属性,另外也实现BeanDefinition接口方法

PS:AbstractBeanDefinition中的方法基本都是get/set/is方法

属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// 默认作用域
public static final String SCOPE_DEFAULT = "";

// 表示没有外部定义的自动装配
public static final int AUTOWIRE_NO = AutowireCapableBeanFactory.AUTOWIRE_NO;

// 通过名称指示自动装配bean属性(适用于Bean所有属性的setter)
public static final int AUTOWIRE_BY_NAME = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME;

// 通过类型指示自动装配bean属性(适用于Bean所有属性的setter)
public static final int AUTOWIRE_BY_TYPE = AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE;

// 构造函数自动装配bean属性
public static final int AUTOWIRE_CONSTRUCTOR = AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR;

// 通过bean类的内省确定适当的自动装配策略,已弃用
@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;

// 依赖检查:对简单类型(8个基本类型、String、集合等)检查
public static final int DEPENDENCY_CHECK_SIMPLE = 2;

// 依赖检查:对所有属性检查
public static final int DEPENDENCY_CHECK_ALL = 3;

public static final String INFER_METHOD = "(inferred)";

// Bean的class对象或是类的全限定名
private volatile Object beanClass;

// bean的作用域
private String scope = SCOPE_DEFAULT;

// 是否是抽象的
private boolean abstractFlag = false;

// 是否延迟加载
private boolean lazyInit = false;

// 自动注入的类型
private int autowireMode = AUTOWIRE_NO;

// 依赖检查
private int dependencyCheck = DEPENDENCY_CHECK_NONE;

// bean依赖项
private String[] dependsOn;

// 如果设置false,那自动装配的时候,就不考虑这个bean
private boolean autowireCandidate = true;

// 当出现多个bean候选的时候,如果为true,则默认为首选的
private boolean primary = false;

// 用于记录qualifier
private final Map<String, AutowireCandidateQualifier> qualifiers =
new LinkedHashMap<String, AutowireCandidateQualifier>(0);

// 允许访问非公开的构造强和方法
private boolean nonPublicAccessAllowed = true;

// 是否以宽松的模式解析构造函数
private boolean lenientConstructorResolution = true;

// 工厂类名(注意是String类型,不是Class类型)
private String factoryBeanName;

// 工厂方法名(注意是String类型,不是Method类型)
private String factoryMethodName;

// 构造函数的注入属性
private ConstructorArgumentValues constructorArgumentValues;

// 普通属性集合
private MutablePropertyValues propertyValues;

// 方法重写的持有者 ,记录Lookup-method、replaced-method元索
private MethodOverrides methodOverrides = new MethodOverrides();

// 初始化方法,对应bean属性的init-method
private String initMethodName;

// 销毁方法,对应bean属性的destroy-method
private String destroyMethodName;

// 是否执行init-method,程序设置
private boolean enforceInitMethod = true;

// 是否执行destroy-method,程序设置
private boolean enforceDestroyMethod = true;

// 创建aop的时候为true
private boolean synthetic = false;

// 定义bean的应用。ROLE_APPLICATION:用户,ROLE_SUPPORT:完全内部使用,与用户无关,ROLE_INFRASTRUCTURE其他复杂的配置。
private int role = BeanDefinition.ROLE_APPLICATION;

// bean的描述
private String description;

// bean的资源
private Resource resource;

构造方法

PS:抽象类的构造方法由子类调用

使用默认设置创建新的AbstractBeanDefinition。

1
2
3
protected AbstractBeanDefinition() {
this(null, null);
}

使用给定的构造函数参数值和属性值创建新的AbstractBeanDefinition

1
2
3
4
protected AbstractBeanDefinition(ConstructorArgumentValues cargs, MutablePropertyValues pvs) {
setConstructorArgumentValues(cargs);
setPropertyValues(pvs);
}

通过给定的BeanDefinition创建新的AbstractBeanDefinition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
protected AbstractBeanDefinition(BeanDefinition original) {
/**
* 调用BeanDefinition接口所声明get/has/is/set方法将属性copy到新的AbstractBeanDefinition中
*/
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);

/**
* 如果给定的参数是AbstractBeanDefinition的子类,调用AbstractBeanDefinition中get/has/is/set方法将属性copy到新的AbstractBeanDefinition中
*/
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());
}
}

addQualifier

1
2
3
public void addQualifier(AutowireCandidateQualifier qualifier) {
this.qualifiers.put(qualifier.getTypeName(), qualifier);
}

addQualifier

新增限定符

1
2
3
public void addQualifier(AutowireCandidateQualifier qualifier) {
this.qualifiers.put(qualifier.getTypeName(), qualifier);
}

applyDefaults

根据参数提供的默认值设置当前对象相应属性

1
2
3
4
5
6
7
8
9
public void applyDefaults(BeanDefinitionDefaults defaults) {
setLazyInit(defaults.isLazyInit());
setAutowireMode(defaults.getAutowireMode());
setDependencyCheck(defaults.getDependencyCheck());
setInitMethodName(defaults.getInitMethodName());
setEnforceInitMethod(false);
setDestroyMethodName(defaults.getDestroyMethodName());
setEnforceDestroyMethod(false);
}

clone

clone方法需要子类重写

1
2
3
4
@Override
public Object clone() {
return cloneBeanDefinition();
}
1
public abstract AbstractBeanDefinition cloneBeanDefinition();

copyQualifiersFrom

将参数AbstractBeanDefinition中的限定符复制到此bean定义

1
2
3
4
public void copyQualifiersFrom(AbstractBeanDefinition source) {
Assert.notNull(source, "Source must not be null");
this.qualifiers.putAll(source.qualifiers);
}

equals

下面重写了hashCode方法,所以要重写equals方法,顺便一提,bean在解析后被存放在一个HashMap中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof AbstractBeanDefinition)) {
return false;
}

AbstractBeanDefinition that = (AbstractBeanDefinition) other;

if (!ObjectUtils.nullSafeEquals(getBeanClassName(), that.getBeanClassName())) return false;
if (!ObjectUtils.nullSafeEquals(this.scope, that.scope)) return false;
if (this.abstractFlag != that.abstractFlag) return false;
if (this.lazyInit != that.lazyInit) return false;

if (this.autowireMode != that.autowireMode) return false;
if (this.dependencyCheck != that.dependencyCheck) return false;
if (!Arrays.equals(this.dependsOn, that.dependsOn)) return false;
if (this.autowireCandidate != that.autowireCandidate) return false;
if (!ObjectUtils.nullSafeEquals(this.qualifiers, that.qualifiers)) return false;
if (this.primary != that.primary) return false;

if (this.nonPublicAccessAllowed != that.nonPublicAccessAllowed) return false;
if (this.lenientConstructorResolution != that.lenientConstructorResolution) return false;
if (!ObjectUtils.nullSafeEquals(this.constructorArgumentValues, that.constructorArgumentValues)) return false;
if (!ObjectUtils.nullSafeEquals(this.propertyValues, that.propertyValues)) return false;
if (!ObjectUtils.nullSafeEquals(this.methodOverrides, that.methodOverrides)) return false;

if (!ObjectUtils.nullSafeEquals(this.factoryBeanName, that.factoryBeanName)) return false;
if (!ObjectUtils.nullSafeEquals(this.factoryMethodName, that.factoryMethodName)) return false;
if (!ObjectUtils.nullSafeEquals(this.initMethodName, that.initMethodName)) return false;
if (this.enforceInitMethod != that.enforceInitMethod) return false;
if (!ObjectUtils.nullSafeEquals(this.destroyMethodName, that.destroyMethodName)) return false;
if (this.enforceDestroyMethod != that.enforceDestroyMethod) return false;

if (this.synthetic != that.synthetic) return false;
if (this.role != that.role) return false;

return super.equals(other);
}

get方法

不具体分析,获取相应的属性,属性详情见上文

image-20200102000909016

hasBeanClass

是否指定bean类

1
2
3
public boolean hasBeanClass() {
return (this.beanClass instanceof Class);
}

hasConstructorArgumentValues

此bean定义的构造函数参数值是否为空

1
2
3
public boolean hasConstructorArgumentValues() {
return !this.constructorArgumentValues.isEmpty();
}

hashCode

返回该对象哈希码

1
2
3
4
5
6
7
8
9
10
11
@Override
public int hashCode() {
int hashCode = ObjectUtils.nullSafeHashCode(getBeanClassName());
hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(this.scope);
hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(this.constructorArgumentValues);
hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(this.propertyValues);
hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(this.factoryBeanName);
hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(this.factoryMethodName);
hashCode = 29 * hashCode + super.hashCode();
return hashCode;
}

hasQualifier

返回此bean是否具有指定的限定符

1
2
3
public boolean hasQualifier(String typeName) {
return this.qualifiers.keySet().contains(typeName);
}

is方法

不具体分析,获取布尔类型属性,属性详情见上文

image-20200102000933089

overrideFrom

类似构造方法,通过给定的BeanDefinition参数,重新设置此bean定义的属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public void overrideFrom(BeanDefinition other) {
/**
* 调用BeanDefinition接口所声明get/has/is/set方法将属性copy到新的AbstractBeanDefinition中,相对构造方法,多了对属性是否为空的判断
*/
if (StringUtils.hasLength(other.getBeanClassName())) {
setBeanClassName(other.getBeanClassName());
}
if (StringUtils.hasLength(other.getScope())) {
setScope(other.getScope());
}
setAbstract(other.isAbstract());
setLazyInit(other.isLazyInit());
if (StringUtils.hasLength(other.getFactoryBeanName())) {
setFactoryBeanName(other.getFactoryBeanName());
}
if (StringUtils.hasLength(other.getFactoryMethodName())) {
setFactoryMethodName(other.getFactoryMethodName());
}
getConstructorArgumentValues().addArgumentValues(other.getConstructorArgumentValues());
getPropertyValues().addPropertyValues(other.getPropertyValues());
setRole(other.getRole());
setSource(other.getSource());
copyAttributesFrom(other);

/**
* 如果给定的参数是AbstractBeanDefinition的子类,调用AbstractBeanDefinition中get/has/is/set方法将属性copy到新的AbstractBeanDefinition中
*/
if (other instanceof AbstractBeanDefinition) {
AbstractBeanDefinition otherAbd = (AbstractBeanDefinition) other;
if (otherAbd.hasBeanClass()) {
setBeanClass(otherAbd.getBeanClass());
}
setAutowireMode(otherAbd.getAutowireMode());
setDependencyCheck(otherAbd.getDependencyCheck());
setDependsOn(otherAbd.getDependsOn());
setAutowireCandidate(otherAbd.isAutowireCandidate());
setPrimary(otherAbd.isPrimary());
copyQualifiersFrom(otherAbd);
setNonPublicAccessAllowed(otherAbd.isNonPublicAccessAllowed());
setLenientConstructorResolution(otherAbd.isLenientConstructorResolution());
getMethodOverrides().addOverrides(otherAbd.getMethodOverrides());
if (StringUtils.hasLength(otherAbd.getInitMethodName())) {
setInitMethodName(otherAbd.getInitMethodName());
setEnforceInitMethod(otherAbd.isEnforceInitMethod());
}
if (otherAbd.getDestroyMethodName() != null) {
setDestroyMethodName(otherAbd.getDestroyMethodName());
setEnforceDestroyMethod(otherAbd.isEnforceDestroyMethod());
}
setSynthetic(otherAbd.isSynthetic());
setResource(otherAbd.getResource());
}
else {
setResourceDescription(other.getResourceDescription());
}
}

prepareMethodOverride

由prepareMethodOverrides方法调用,验证并准备给定的方法重载。检查指定名称的方法是否存在,如果没有找到方法,则将其标记为未重载。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
protected void prepareMethodOverride(MethodOverride mo) throws BeanDefinitionValidationException {
// 统计注入的方法个数
int count = ClassUtils.getMethodCountForName(getBeanClass(), mo.getMethodName());
// 如果为0,则抛出异常
if (count == 0) {
throw new BeanDefinitionValidationException(
"Invalid method override: no method with name '" + mo.getMethodName() +
"' on class [" + getBeanClassName() + "]");
}
// 如果为1,则将注入方法标记为未重载
// 注意:当有多个重载方法时,为了确定调用哪个具体的方法,Spring对重载方法的参数解析是很复杂的
// 所以,如果注入方法没有被重载这里就将其标记,省去了对方法参数的解析过程,直接调用即可
else if (count == 1) {
mo.setOverloaded(false);
}
}

prepareMethodOverrides

prepareMethodOverrides方法循环调用了prepareMethodOverride方法,验证方法重写

1
2
3
4
5
6
7
8
9
10
11
public void prepareMethodOverrides() throws BeanDefinitionValidationException {
MethodOverrides methodOverrides = getMethodOverrides();
if (!methodOverrides.isEmpty()) {
Set<MethodOverride> overrides = methodOverrides.getOverrides();
synchronized (overrides) {
for (MethodOverride mo : overrides) {
prepareMethodOverride(mo);
}
}
}
}

resolveBeanClass

1
2
3
4
5
6
7
8
9
public Class<?> resolveBeanClass(ClassLoader classLoader) throws ClassNotFoundException {
String className = getBeanClassName();
if (className == null) {
return null;
}
Class<?> resolvedClass = ClassUtils.forName(className, classLoader);
this.beanClass = resolvedClass;
return resolvedClass;
}

set方法

也不具体分析,设置相应的属性,属性详情见上文

image-20200102000948222

toString

对象转字符串,基本上就是拼接AbstractBeanDefinition的一些属性输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Override
public String toString() {
StringBuilder sb = new StringBuilder("class [");
sb.append(getBeanClassName()).append("]");
sb.append("; scope=").append(this.scope);
sb.append("; abstract=").append(this.abstractFlag);
sb.append("; lazyInit=").append(this.lazyInit);
sb.append("; autowireMode=").append(this.autowireMode);
sb.append("; dependencyCheck=").append(this.dependencyCheck);
sb.append("; autowireCandidate=").append(this.autowireCandidate);
sb.append("; primary=").append(this.primary);
sb.append("; factoryBeanName=").append(this.factoryBeanName);
sb.append("; factoryMethodName=").append(this.factoryMethodName);
sb.append("; initMethodName=").append(this.initMethodName);
sb.append("; destroyMethodName=").append(this.destroyMethodName);
if (this.resource != null) {
sb.append("; defined in ").append(this.resource.getDescription());
}
return sb.toString();
}

validate

校验当前对象

1
2
3
4
5
6
7
8
9
10
11
12
public void validate() throws BeanDefinitionValidationException {
//
if (!getMethodOverrides().isEmpty() && getFactoryMethodName() != null) {
throw new BeanDefinitionValidationException(
"Cannot combine static factory method with method overrides: " +
"the static factory method must create the instance");
}
// 当前对象beanClass如果不为空,执行方法重载校验
if (hasBeanClass()) {
prepareMethodOverrides();
}
}

总结

总的来说,AbstractBeanDefinition实现了BeanDefinition接口的方法,定义了Bean的描述信息(例如是否是抽象类、是否单例)、depends-on属性(String类型,不是Class类型)、自动装配的相关信息、init函数、destroy函数的名字(String类型)、工厂方法名、工厂类名(String类型,不是Class类型)、构造函数形参的值、被IOC容器覆盖的方法、Bean的属性以及对应的值(在初始化后会进行填充)等一系列属性,同时这是一个抽象类,基于该类,可以进一步封装

-------------本文结束感谢您的阅读-------------