从源码了解spring bean实例化过程

初始化示例

我们先来看下spring如何手动初始化一个对象

1
2
3
4
5
ClassPathResource res = new ClassPathResource("beans.xml");
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
reader.loadBeanDefinitions(res);
User user=(User) factory.getBean("user");

Paste_Image.png

spring源码解析

所以我们先从DefaultListableBeanFactory开始了解

AbstractBeanFactory

1
2
3
public <T> T getBean(String name, Class<T> requiredType, Object... args) throws BeansException {
return doGetBean(name, requiredType, args, false);
}
1
2
3
protected <T> T doGetBean(final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
throws BeansException {

  • 1.去掉&开头
1
final String beanName = transformedBeanName(name);
1
2
3
protected String transformedBeanName(String name) {
return canonicalName(BeanFactoryUtils.transformedBeanName(name));
}
  • 2.如果是单例且存在,就直接取过来
1
2
3
4
5
6
7
Object bean;
//拿到缓存的单例实例
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
....
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
  • 3.不存在单例缓存里面却处于创建状态,可能是循环引用,抛出异常
1
2
3
4
5
6
else {
//可能是一个循环引用,因为拿不到bean但是却处于创建状态
if (isPrototypeCurrentlyInCreation(beanName)) {
//Requested bean is currently in creation: Is there an unresolvable circular reference?
throw new BeanCurrentlyInCreationException(beanName);
}
  • 4.在父BeanFactory查找
1
2
3
4
5
6
7
8
9
10
11
12
13
14
			BeanFactory parentBeanFactory = getParentBeanFactory();
//本beanfactory找不到
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// 找不到拿原始名去找
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);
}
}
  • 5.创建标记,(用于清除)
1
2
3
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
  • 6.寻找bean定义信息,并针对bean定义进行验证
1
2
3
try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
  • 7.处理依赖信息,这里会针对xml定义中的depends-on进行处理
1
2
3
4
5
6
7
8
9
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dependsOnBean : dependsOn) {
if (isDependent(beanName, dependsOnBean)) {
....
registerDependentBean(dependsOnBean, beanName);
getBean(dependsOnBean);
}
}

具体通过这个私有方法来解决依赖的
假设A依赖于B,那么在创建A之前,必须保证B先被创建。
在创建了B之后,这里会进行依赖信息存储。后面在递归调用一下,不过依赖关系反过来。
dependentBeanMap放 A->[B,C,D] (A所依赖的B,C,D)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
private boolean isDependent(String beanName, String dependentBeanName, Set<String> alreadySeen) {
if (alreadySeen != null && alreadySeen.contains(beanName)) {
return false;
}
String canonicalName = canonicalName(beanName);
Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);
if (dependentBeans == null) {
return false;
}
if (dependentBeans.contains(dependentBeanName)) {
return true;
}
for (String transitiveDependency : dependentBeans) {
if (alreadySeen == null) {
alreadySeen = new HashSet<String>();
}
alreadySeen.add(beanName);
if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) {
return true;
}
}
return false;
}

单例模式就调用getSingleton(String beanName, ObjectFactory<?> singletonFactory)

1
2
3
4
5
// 单例
if (mbd.isSingleton()) {
....
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
	public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
....
//private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);
synchronized (this.singletonObjects) {
Object singletonObject = this.singletonObjects.get(beanName);
....
beforeSingletonCreation(beanName);
....
singletonObject = singletonFactory.getObject();
....
addSingleton(beanName, singletonObject);

}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
}

原型模式,来一次创一个

1
2
3
4
5
6
7
8
9
10
11
else if (mbd.isPrototype()) {
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}

其他模式,比如scope=request

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
				else {
String scopeName = mbd.getScope();
//private final Map<String, Scope> scopes = new LinkedHashMap<String, Scope>(8);
final Scope scope = this.scopes.get(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);
}
....
}
}
....
}
  • 8.无论哪种模式都会进入AbstractAutowireCapableBeanFactory的createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)

    类会被包装成一个RootBeanDefinition

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
              ....
RootBeanDefinition mbdToUse = mbd;
// 解析beanDefinition,以确保bean定义中的class可以被正确解析,这里拷贝一个是为了防止多线程修改
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}

// 准备和验证配置的方法注入,若验证失败抛出BeanDefinitionValidationException
try {
mbdToUse.prepareMethodOverrides();
}
....

try {
// 如果实现了InstantiationAwareBeanPostProcessor就先postProcessBeforeInstantiation(Class<?> beanClass, String beanName)->postProcessAfterInitialization(Object bean, String beanName)
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
....

Object beanInstance = doCreateBean(beanName, mbdToUse, args);
....
}
return beanInstance;
  • 9.Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
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
if (instanceWrapper == null) {
//反射出类
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
mbd.resolvedTargetType = beanType;

// 同步,
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
//获取所有MergedBeanDefinitionPostProcessor,调用一遍postProcessMergedBeanDefinition
//找出所有的字段或者方法上的@Autowired @Value @Inject @PostConstruct注解加入到BeanDefinition
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
....
//InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation
//InstantiationAwareBeanPostProcessor#postProcessPropertyValues
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
....

10.Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd)

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
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
//setBeanName#BeanNameAware
//->setBeanClassLoader#BeanClassLoaderAware
//->setBeanFactory#BeanFactoryAware
invokeAwareMethods(beanName, bean);
return null;
}
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}

Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
//->postProcessBeforeInitialization#BeanPostProcessor
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}

try {
//->afterPropertiesSet#InitializingBean
invokeInitMethods(beanName, wrappedBean, mbd);
}
....

if (mbd == null || !mbd.isSynthetic()) {
//->postProcessAfterInitialization#BeanPostProcessor
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
1
2
3
4
5
6
7
8
9
10
11
12
13
private void invokeAwareMethods(final String beanName, final Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
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 void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable {

boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
....
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
((InitializingBean) bean).afterPropertiesSet();
return null;
}
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
((InitializingBean) bean).afterPropertiesSet();
}
}

if (mbd != null) {
String initMethodName = mbd.getInitMethodName();
if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
  • 10.destroyBean
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
@Override
public void destroyBean(Object existingBean) {
new DisposableBeanAdapter(existingBean, getBeanPostProcessors(), getAccessControlContext()).destroy();
}

@Override
public void destroy() {
if (!CollectionUtils.isEmpty(this.beanPostProcessors)) {
//获取所有DestructionAwareBeanPostProcessor 调用postProcessBeforeDestruction
//@PreDestroy
for (DestructionAwareBeanPostProcessor processor : this.beanPostProcessors) {
processor.postProcessBeforeDestruction(this.bean, this.beanName);
}
}

//调用DisposableBean#destroy
if (this.invokeDisposableBean) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking destroy() on bean with name '" + this.beanName + "'");
}
try {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
((DisposableBean) bean).destroy();
return null;
}
}, acc);
}
else {
((DisposableBean) bean).destroy();
}
}
catch (Throwable ex) {
String msg = "Invocation of destroy method failed on bean with name '" + this.beanName + "'";
//...
}
}
//xml的destroy-method
if (this.destroyMethod != null) {
invokeCustomDestroyMethod(this.destroyMethod);
}
else if (this.destroyMethodName != null) {
Method methodToCall = determineDestroyMethod();
if (methodToCall != null) {
invokeCustomDestroyMethod(methodToCall);
}
}
}
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
public class InitAndDestroySeqBean implements InitializingBean,DisposableBean,BeanPostProcessor,InstantiationAwareBeanPostProcessor {

public InitAndDestroySeqBean() {
System.out.println("构造方法");
}

@PostConstruct
public void postConstruct(){
System.out.println("@PostConstruct");
}

@Override public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet()#InitializingBean");

}

public void initMethod(){
System.out.println("init-method");

}

@PreDestroy
public void preDestroy(){
System.out.println("@PreDestroy");
}


@Override public void destroy() throws Exception {
System.out.println("destroy()#DisposableBean");
}


public void destroyMethod(){
System.out.println("destroy-method");
}


@Override public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("postProcessBeforeInitialization(Object bean, String beanName)#BeanPostProcessor");
return bean;
}


@Override public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("postProcessAfterInitialization(Object bean, String beanName)#BeanPostProcessor");
return bean;
}


@Override public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName)
throws BeansException {
System.out.println("postProcessBeforeInstantiation(Class<?> beanClass, String beanName)#InstantiationAwareBeanPostProcessor");
return null;
}


@Override public boolean postProcessAfterInstantiation(Object bean, String beanName)
throws BeansException {
System.out.println("postProcessAfterInstantiation(Object bean, String beanName)#InstantiationAwareBeanPostProcessor");

return false;
}


@Override public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds,
Object bean, String beanName) throws BeansException {
System.out.println("postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds,\n"
+ " Object bean, String beanName)#InstantiationAwareBeanPostProcessor");

return null;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20170308:11:34:52.866 [main] INFO   Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@49c43f4e, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@290dbf45, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@12028586, org.springframework.test.context.support.DirtiesContextTestExecutionListener@17776a8, org.springframework.test.context.transaction.TransactionalTestExecutionListener@69a10787, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@2d127a61]20170308:11:34:52.972 [main] INFO   Loading XML bean definitions from URL [file:/Users/dsc/IdeaProjects/firDemo/firdemo/web/target/classes/init.xml]
20170308:11:34:53.105 [main] INFO Refreshing org.springframework.context.support.GenericApplicationContext@2b4a2ec7: startup date [Wed Mar 08 11:34:53 CST 2017]; root of context hierarchy
构造方法
@PostConstruct
afterPropertiesSet()#InitializingBean
init-method
beanName)#InstantiationAwareBeanPostProcessor**guavaCache
postProcessAfterInstantiation(Object bean, String beanName)#InstantiationAwareBeanPostProcessor**guavaCache
postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds,
Object bean, String beanName)#InstantiationAwareBeanPostProcessor**guavaCache
postProcessBeforeInitialization(Object bean, String beanName)#BeanPostProcessor**guavaCache
afterPropertiesSet#InitializingBean**guavaCache
postProcessAfterInitialization(Object bean, String beanName)#BeanPostProcessor**guavaCache
20170308:11:34:53.286 [Thread-0] INFO Closing org.springframework.context.support.GenericApplicationContext@2b4a2ec7: startup date [Wed Mar 08 11:34:53 CST 2017]; root of context hierarchy
@PreDestroy
destroy()#DisposableBean
destroy-method


Spring生命周期

通过源码我们清晰的看到

  1. 拿到应用中所有实现了InstantiationAwareBeanPostProcessor接口的类,就先postProcessBeforeInstantiation(Class<?> beanClass, String beanName)->postProcessAfterInitialization(Object bean, String beanName)

如果已经能拿到相应的bean则直接返回不进行下面的操作

  1. 反射实例化bean

  2. 拿到应用中所有实现了InstantiationAwareBeanPostProcessor调用postProcessAfterInstantiation,然后调用postProcessPropertyValues

  3. 本bean如果

  • 实现了BeanNameAware就调用setBeanName把bean名字放入

  • 实现了BeanClassLoaderAware就调用setBeanClassLoader把ClassLoader放入

  • 实现了BeanFactoryAware调用setBeanFactory把BeanFactory放入

  1. 拿到应用中所有实现了BeanPostProcessor接口的类,调用postProcessBeforeInstantiation(Class<?> beanClass, String beanName)拿到bean (@PostConstruct注解的方法)
  2. 本bean如果实现了InitializingBean接口,则调用afterPropertiesSet
  3. 本bean如果在xml里面配置了init-method则调用
  4. 拿到应用中所有实现了BeanPostProcessor接口的类,调用postProcessAfterInitialization(Object bean, String beanName) 拿到bean返回,就是最终在容器里面的bean
  5. @PreDestroy注解的方法(获取所有DestructionAwareBeanPostProcessor 调用postProcessBeforeDestruction)
  6. 本bean如果实现了DisposableBean则调用destroy()
  7. 本bean如果在xml里面配置了destroy-method则调用

刚才反复提到了几个接口,我们来单独看下他们的使用:

InstantiationAwareBeanPostProcessor接口

1
2
3
4
5
6
7
public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException;

boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException;

PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException;
}

BeanNameAware接口,通过实现这个接口可以获取到bean的id名

1
2
3
public interface BeanNameAware extends Aware {
void setBeanName(String name);
}

BeanClassLoaderAware接口,可以获取到bean的ClassLoader

1
2
3
public interface BeanClassLoaderAware extends Aware {
void setBeanClassLoader(ClassLoader classLoader);
}

BeanFactoryAware接口,通过实现这个接口可以获取到beanFactory

1
2
3
public interface BeanFactoryAware extends Aware {
void setBeanFactory(BeanFactory beanFactory) throws BeansException;
}

ApplicationContextAware接口,获取ApplicationContext

1
2
3
public interface ApplicationContextAware extends Aware {
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}

BeanPostProcessor接口

1
2
3
4
5
public interface BeanPostProcessor {
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;

Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}

InitializingBean接口

1
2
3
public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}

DisposableBean接口

1
2
3
public interface DisposableBean {
void destroy() throws Exception;
}

MergedBeanDefinitionPostProcessor接口

1
2
3
public interface MergedBeanDefinitionPostProcessor extends BeanPostProcessor {
void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName);
}

DestructionAwareBeanPostProcessor接口

1
2
3
4
5
public interface DestructionAwareBeanPostProcessor extends BeanPostProcessor {
void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException;

boolean requiresDestruction(Object bean);
}