Spring生成bean的过程

spring是java程序员的春天,很多人写完helloworld后就转入了spring的怀抱。现在来了解一下bean是怎么创建的吧。

这里假设你已经对java比较了解,类反射代理之类的也有所涉猎。否则建议先了解一下类的反射。

如何定义Bean

假设你在写一个类Dog,Dog有年龄age,名字name,它还可以say。以下是实现代码:

1
2
3
4
5
6
7
8
9
10
11
12
public class Dog {
public Integer age;
public String name;

public void say(){
System.out.println("my name is "+name+" . age is "+age);
}

public static void main(String[] args) {
new Dog().say();
}
}

我们来看看怎么描述我们想要创建的Dog。

类名

类名肯定得有,到时候通过Class#forName()方法可以加载到这个类。

实例别名

如果你不想通过类名来描述一个实例,又或是这个类有多个实例,这时候就需要一个实例别名来描述了。

构造函数

如果你希望通过向特定的构造函数传入入参来创建实例,那么你得描述到底使用哪个构造函数,简单的可以通过每个参数的类型,来判断。然而,如果你的入参是通过别的bean定义得来的,那你可得考虑两个实例的生成关系了。

属性设置

就像这个Dog类,不用向构造函数传参即可new出来,那如果想在实例生成后设置上属性该怎么做呢?是不是得标记一下你想给哪个属性设置什么值。

初始化方法

你的实例生成了,属性也设置上了,你想让他试着叫一下,是不是得指定say方法在实例化后执行?

销毁方法

假如你的Dog连接了一些资源,在下线时需要销毁,是不是得指定方法在系统执行完后执行?

其他方面,读者可以再考虑一下。

BeanDefinition

在第一小节中,大家大致了解了对于一个对象该怎么描述。为什么需要考虑对象的描述呢?因为使用spring就会把对象的生成交给spring,spring需要知道对象该怎么生成。

在spring中,BeanDefinition就是描述对象的类。在getBean时,spring通过对BeanDefinition列表的扫描得知你需要哪一个bean,进而生成bean返回给你。

通过代码生成BeanDefinition

最普通的情况就是通过xml生成了,spring通过对xml的读取解析得到用户写的bean配置,想一想第一小节中那些描述点都在spring的xml配置的哪些地方。

实际上也可以通过代码生成:

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
public class Dog {
public Integer age;
public String name;

public void say(){
System.out.println("my name is "+name+" . age is "+age);
}

public void setAge(Integer age) {
this.age = age;
}

public void setName(String name) {
this.name = name;
}

public static void main(String[] args) {
new Dog().say();

// 准备生成dog的定义
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(Dog.class);
// 设置它的属性
builder.addPropertyValue("name","john");
builder.addPropertyValue("age",1);

// 生成beanFactory
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();

// 添加dog定义
beanFactory.registerBeanDefinition("dog",builder.getBeanDefinition());

// 获取dog
Dog dog = (Dog) beanFactory.getBean("dog");
dog.say();
}
}

结果如下:

1
2
my name is null . age is null
my name is john . age is 1

通过xml生成BeanDefinition

xml生成BeanDefinition无非是原先用代码描述的BeanDefinition换成用xml描述,至于怎么读取xml,spring有自己的方法。而xml的解析技术一般分为两种 DOM SAX

DOM方式

根据XML的层级结构在内存中分配一个树形结构,把XML的标签,属性和文本等元素都封装成树的节点对象

  • 优点: 便于实现增 删 改 查
  • 缺点: XML文件过大可能造成内存溢出

SAX方式

采用事件驱动模型边读边解析:从上到下一行行解析,解析到某一元素, 调用相应解析方法

  • 优点: 不会造成内存溢出,
  • 缺点: 查询不方便,但不能实现 增 删 改

具体如何解析这里就不深究了,重点是你可以从xml节点上读取相关信息生成BeanDefinition

实际使用

实际上,DefaultListableBeanFactory不具备从xml配置中获取BeanDefinition,它只能通过代码的方式注册。我们应用一般采用ApplicationContext的实现类FileSystemXmlApplicationContext,ClassPathXmlApplicationContextWebXmlApplicationContext来从xml中获取BeanDefinition,并注册到自身的属性BeanFactory中。ClassPathXmlApplicationContext的类关系图如下:

upload successful

在生成ClassPathXmlApplicationContext对象时,构造函数入参会传入具体xml配置文件的位置,可以是单个,也可以是多个,也可以包含匹配符。

接着会调用AbstractApplicationContext的refresh方法。refresh方法中会调用自身方法obtainFreshBeanFactory来获取生成的Bean。

obtainFreshBeanFactory方法会调用AbstractRefreshableApplicationContext的refreshBeanFactory方法。这个方法的作用是销毁已有beanFactory中的bean,并且关闭beanFactory。接着会去生成一个DefaultListableBeanFactory对象,最后使用loadBeanDefinitions方法从xml配置中加载BeanDefinition。

实际上AbstractXmlApplicationContext实现了loadBeanDefinitions方法,在这个方法里,使用了XmlBeanDefinitionReader对象来读取xml配置信息并转换成BeanDefinition。XmlBeanDefinitionReader采用SAX方式读取xml。

生成Bean对象

上边两个小节描述了Bean的定义,接下来就是重头了,如何生成Bean对象,spring又是如何让生成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
public class Dog {
protected Integer age;
public String name;

public void say(){
System.out.println("my name is "+name+" . age is "+age);
}

public void setAge(Integer age) {
this.age = age;
}

public void setName(String name) {
this.name = name;
}

public static void main(String[] args) {
try {
// 获取Dog类
Class dogClass = Class.forName("Dog");
// 通过类生成对象
Dog dog1 = (Dog) dogClass.newInstance();
// 获取特定的属性
Field field = dogClass.getField("name");
// 填充属性
field.set(dog1,"landa");
dog1.say();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

}
}

结果:

1
my name is landa . age is null

以上代码演示了如何不通过new的方式生成对象,并且给对象设置上属性值。可以说,spring做的一切都是基于java的反射。

BeanFactory类图

upload successful

AbstractBeanFactory#doGetBean方法

DefaultListableBeanFactory的getBean方法最终会调用AbstractBeanFactory的doGetBean方法。

doGetBean方法执行流程:

先整理入参的name到beanName(transformedBeanName)//TODO

然后尝试从属性singletonObjects获取beanName对应的对象。

如果不是null,并且入参args是null:

//TODO

如果获取的对象是null,或者args不是null:

先判断这个bean在当前线程是否已经创建,如果已经创建,则抛出异常。(一般情况下不会出现这种情况)

接着如果当前的beanFactory没有对应的beanName的BeanDefinition并且当前的beanFactory有父beanFactory,那就调用父beanFactory的doGetBean方法生成bean。(一般情况下没有)

根据入参决定是否要标记bean已经被创建(一般情况下都会要标记),标记方法是如果属性alreadyCreated中没有包含该beanName,则清除属性mergedBeanDefinitions中这个beanName对应的BeanDefinition,将该beanName加入到属性alreadyCreated中。

接下来就是要获取mergedBeanDefinition了,上一条我们在属性mergedBeanDefinitions中删除了相关的BeanDefinition,所以beanFactory会根据注册在属性beanDefinitionMap的BeanDefinition重新创建RootBeanDefinition到mermergedBeanDefinitions中(如果beanDefinition没有说明是原型模式就给bean标识为单例就是在这时候做的)。

接下来是一个比较重要的事情,要获取这个beanName对应对象的依赖对象,先生成依赖对象,不允许两个bean相互绝对依赖(TODO例如两个类的唯一构造函数入参中都有对方的类)。

接下来根据bean定义中的单例还是原型,分两类来分别生成。

单例情况->走AbstractAutowireCapableBeanFactory的createBean方法

原型情况->beforePrototypeCreation(beanName)(清除已有信息,为createBean打下基础);prototypeInstance = createBean(beanName, mbd, args);最后清除生成数据的信息。

最后,如果需要的类和生成对象所在的类不是父子关系,还要走一个TypeConverter。(TODO)

doGetBean方法:

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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
protected <T> T doGetBean( final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
throws BeansException {

final String beanName = transformedBeanName(name);
Object bean;

// Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isDebugEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}

else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}

// Check if bean definition exists in this factory.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}

if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}

try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);

// Guarantee initialization of beans that the current bean depends on.
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dependsOnBean : dependsOn) {
if (isDependent(beanName, dependsOnBean)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'");
}
registerDependentBean(dependsOnBean, beanName);
getBean(dependsOnBean);
}
}

// Create bean instance.
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}

else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}

else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}

// Check if required type matches the type of the actual bean instance.
if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
try {
return getTypeConverter().convertIfNecessary(bean, requiredType);
}
catch (TypeMismatchException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to convert bean '" + name + "' to required type [" +
ClassUtils.getQualifiedName(requiredType) + "]", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}

AbstractAutowireCapableBeanFactory#createBean方法

createBean方法执行流程:

入参是beanName,RootBeanDefinition,和args

根据rootBeanDefinition和beanName获取beanName对应的类(TODO)

Prepare method overrides.(TODO)

重要的一环到了,给BeanPostProcessors一个机会去创建一个代理实例

调用AbstractAutowireCapableBeanFactory的resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd))方法。

如果属性hasInstantiationAwareBeanPostProcessors不为false且bean定义表名这个bean不是系统合成的。

则根据beanName和beanDefinition获取实际需要创建的类Class,

调用属性beanPostProcessors中所有实现InstantiationAwareBeanPostProcessor接口的对象postProcessBeforeInstantiation方法,逐个调用如果有一个方法产生bean就返回。

如果上述操作返回了bean,那就继续调用属性beanPostProcessors中所有对象的postProcessAfterInitialization方法。逐个调用,一旦有一个方法返回null,则返回null,否则,返回方法生成的bean。

最后,如果通过BeanPostProcessors生成了bean,则把bean定义中的beforeInstantiationResolved设置为true。

最后不管是否成功创建bean,都返回bean。(这里单独强调一下BeanPostProcessorsBeforeInstantiation和BeanPostProcessorsAfterInitialization,如果可以调方法,则会从beanFactory.beanPostProcessors中获取所有beanPostProcessors,挨个执行,其中,如果有实现InstantiationAwareBeanPostProcessor接口的,则调用postProcessBeforeInstantiation方法,如果这个方法生成了bean,就返回,否则继续循环直到结束,最后返回null,BeanPostProcessorsAfterInitialization则也是挨个执行postProcessAfterInitialization方法,但凡有一个返回null,则返回null,否则继续执行,最后返回null)

上边操作一旦没有产生bean,那么就走普通流程doCreateBean方法

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
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;

// Make sure bean class is actually resolved at this point, and
// clone the bean definition in case of a dynamically resolved Class
// which cannot be stored in the shared merged bean definition.
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}

// Prepare method overrides.
try {
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}

try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}

Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}

AbstractAutowireCapableBeanFactory#doCreateBean方法

doCreateBean方法执行流程:

入参是beanName,RootBeanDefinition,和args

如果这个bean定义是单例的,则会先从属性factoryBeanInstanceCache中删除beanName对应的bean。

如果这个bean不是单例或者属性factoryBeanInstanceCache中没有,则会走createBeanInstance方法生成bean。

生成bean后,允许MergedBeanDefinitionPostProcessor再去执行postProcessMergedBeanDefinition方法修改bean定义

接下来判断是否要提早加入到属性singletonFactories,属性registeredSingletons中,并且从earlySingletonObjects中移除。这里可以使用SmartInstantiationAwareBeanPostProcessor接口的getEarlyBeanReference方法再处理生成的bean。//TODO

使用populateBean方法填充属性

接下来走initializeBean方法初始化对象

接下来,让有循环依赖的bean真正依赖生成的bean。//TODO具体怎么处理还待探究

最后注册一下bean是否需要销毁动作,这里会注入多个DestructionAwareBeanPostProcessor接口实现类,如果其中一个实现类的requiresDestruction方法判断这个bean是否可以使用让这个实现类销毁。如果可以则注册一个销毁回调,在销毁前调用这个实现类的postProcessBeforeDestruction方法。

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
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);

// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
mbd.postProcessed = true;
}
}

// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
return getEarlyBeanReference(beanName, mbd, bean);
}
});
}

// Initialize the bean instance.
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}

if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}

// Register bean as disposable.
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}

return exposedObject;
}

AbstractAutowireCapableBeanFactory#createBeanInstance方法

createBeanInstance方法执行流程

入参是beanName,RootBeanDefinition,和args

根据beanName和bean定义获取实际创建类Class。

如果这个bean定义表示这个bean是通过工厂方法创建的,那么就走instantiateUsingFactoryMethod方法生成bean(TODO)

否则通过SmartInstantiationAwareBeanPostProcessor接口的determineCandidateConstructors方法获取这个bean类的构造函数列表,如果构造函数存在或bean定义里表示能够自动装配或bean定义中有构造函数的值,或者入参的args不是空的,则采用自动装配构造器方法生成bean(autowireConstructor),否则采用简单的无参数方法生成bean(instantiateBean)。//TODO

生成完bean后,需要用beanWrapper将获取到的bean包装起来,然后返回这个beanWrapper。

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
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
// Make sure bean class is actually resolved at this point.
Class<?> beanClass = resolveBeanClass(mbd, beanName);

if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
}

if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}

// Shortcut when re-creating the same bean...
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
if (autowireNecessary) {
return autowireConstructor(beanName, mbd, null, null);
}
else {
return instantiateBean(beanName, mbd);
}
}

// Need to determine the constructor...
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}

// No special handling: simply use no-arg constructor.
return instantiateBean(beanName, mbd);
}

AbstractAutowireCapableBeanFactory#populateBean方法

populateBean方法执行流程:

这个方法用来给bean填充属性的,这里可以再执行属性beanPostProcessors中实现InstantiationAwareBeanPostProcessor接口的类postProcessAfterInstantiation方法,如果有任意一个接口实现类执行该方法返回false,就不会再执行属性填充。

如果bean定义中表示根据name或者type自动装配,那就根据name或type设置上属性propertyValues。

接下来这里还可以执行InstantiationAwareBeanPostProcessor的postProcessPropertyValues方法来处理propertyValues,如果该方法返回了null,那也不会再进行属性填充。

applyPropertyValues最终进行属性装配。

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
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
PropertyValues pvs = mbd.getPropertyValues();

if (bw == null) {
if (!pvs.isEmpty()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
// Skip property population phase for null instance.
return;
}
}

// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
boolean continueWithPropertyPopulation = true;

if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}

if (!continueWithPropertyPopulation) {
return;
}

if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

// Add property values based on autowire by name if applicable.
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}

// Add property values based on autowire by type if applicable.
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}

pvs = newPvs;
}

boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);

if (hasInstAwareBpps || needsDepCheck) {
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
}
if (needsDepCheck) {
checkDependencies(beanName, mbd, filteredPds, pvs);
}
}

applyPropertyValues(beanName, mbd, bw, pvs);
}

AbstractAutowireCapableBeanFactory#initializeBean方法

initializeBean方法执行流程:

首先会根据对象类是否实现BeanNameAware或BeanClassLoaderAware或BeanFactoryAware从而设置相应属性。

接下来循环执行属性beanPostProcessors中每一个BeanPostProcessor实现类的postProcessBeforeInitialization方法,如果有一个方法返回null,则会返回null,应用将会抛异常。

接下来如果bean实现了InitializingBean接口会去调用afterPropertiesSet方法或bean定义设置的init_methed方法通过反射执行初始化方法。

接下来循环执行属性beanPostProcessors中每一个BeanPostProcessor实现类的postProcessAfterInitialization方法,如果有一个方法返回null,则会返回null。

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
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
invokeAwareMethods(beanName, bean);
return null;
}
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}

Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}

try {
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}

if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}

小结

getBean方法

doGetBean方法

createBean方法

尝试通过InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation生成bean并调用BeanPostProcessor#postProcessAfterInitialization方法,最后得到了bean则返回

否则调用doCreateBean方法

调用createBeanInstance方法,可以走工厂方法就走工厂方法。否则尝试SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors得到合适的构造器,或者有定义入参,采用自动装配构造器方法生成。否则采用newInstance生成bean。

调用#populateBean方法,执行InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation判断是否继续属性填充,设置定义好值的属性,执行InstantiationAwareBeanPostProcessor#postProcessPropertyValues方法来处理propertyValues,applyPropertyValues最终进行属性装配。

调用initializeBean方法,设置BeanNameAware或BeanClassLoaderAware或BeanFactoryAware,调用BeanPostProcessor#postProcessBeforeInitialization。调用InitializingBean接口afterPropertiesSet方法,调用bean设置的init_methed方法,调用BeanPostProcessor#postProcessAfterInitialization方法。

返回最终生成的bean

判断bean是否要销毁,如果需要则加入销毁回调。