# spring beans
# spring bean的生命周期
bean的声明周期分为如下几个阶段,在这些阶段的前后spring都预留了回调接口,比如各种postProcessor
- Bean Definition扫描、注册
- Bean实例化: 实例化就是创建bean对象的过程,比如通过构造函数或通过FactoryBean方法创建
- Bean初始化: 对字段进行注入比如@Autowired的字段,执行@PostConstruct方法、实现InitializationBean的bean会调用afterPropertiesSet方法等
- Bean销毁: bean销毁前,也可以做一些比如资源释放清理的工作,一般发生在jvm关闭的时候
# Bean Definition扫描、注册
BeanFactory默认的实现类是DefaultListableBeanFactory,提供了registerBeanDefinition的实现。 在通过扫描包注册component的情况下,是通过ConfigurationClassPostProcessor在postProcessBeanRegistry时通过ClassPathBeanDefinitionScanner 扫描解析指定包下的BeanDefinition并注册到BeanFactory中。 还有另一种方式是通过其他的BeanFactoryPostProcessor注册BeanDefinition,比如mybatis通过MapperScannerConfigurer扫描注册mybatis的Mapper bean。
bean definition 注册后,就可以通过getBean获取bean了,BeanFactory会负责创建bean、保存singleton等。
# bean实例化
bean创建的触发时机,是通过BeanFactory的getBean方法触发,如果是singleton(单例,也是默认的类型)类型的bean, 并且BeanFactory的singleton map里没有这个bean,会触发创建过程。
如下面代码所示,doGetBean会先调用getSingleton,如果singleton缓存中有结果,并且bean的创建参数为空,则调用getObjectForBeanInstance 判断是否是factory bean如果不是factory bean直接返回,如果是factory bean也先去factory bean cache中查询,没有调用FactoryBean的getObject方法获取bean并缓存。
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable 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.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
其他情况(singleton 缓存里没有或args不为null),先做个循环依赖检查(当前的bean正在创建过程中)
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
2
3
4
5
6
然后判断下是singleton类型,调用getSingleton触发bean创建并保存singleton
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
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);
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
getSingleton方法,要加锁做好并发处理,避免并发创建bean。 beforeSingletonCreation会在singletonsCurrentlyInCreation 这个set中添加判断是否是循环依赖的情况。 然后调用singletonFactory.getObject(),也就是createBean方法创建bean。
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
afterSingletonCreation(beanName);
}
if (newSingleton) {
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
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
createBean方法先调用resolveBeanClass解析加载bean的Class。
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isTraceEnabled()) {
logger.trace("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);
2
3
4
5
6
7
8
9
10
11
12
然后调用resolveBeforeInstantiation调用InstantiationAwareBeanPostProcessor的postProcessBeforeInstantiation方法。
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;
}
}
2
3
4
5
6
7
有一些InstantiationAwareBeanPostProcessor可能会在postProcessBeforeInstantiation返回bean, 比如aop有targetSource的情况,如果postProcessBeforeInstantiation返回了bean,就不用后面的bean创建流程了, 直接调用BeanPostProcessor的postProcessAfterInitialization。
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
postProcessBeforeInstantiation没有创建bean的情况,调用doCreateBean
try {
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
2
3
4
5
6
7
doCreateBean首先通过createBeanInstance创建bean对象,通过参数匹配构造函数,通过CglibSubclassingInstantiationStrategy创建bean实例。
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
2
3
4
5
6
7
8
9
10
11
对应的bean没有MethodOverrides的情况下使用反射创建对象,否则使用cglib创建子类创建对象。
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
// Don't override the class with CGLIB if no overrides.
if (!bd.hasMethodOverrides()) {
Constructor<?> constructorToUse;
synchronized (bd.constructorArgumentLock) {
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
if (constructorToUse == null) {
final Class<?> clazz = bd.getBeanClass();
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
if (System.getSecurityManager() != null) {
constructorToUse = AccessController.doPrivileged(
(PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
}
else {
constructorToUse = clazz.getDeclaredConstructor();
}
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch (Throwable ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
}
}
return BeanUtils.instantiateClass(constructorToUse);
}
else {
// Must generate CGLIB subclass.
return instantiateWithMethodInjection(bd, beanName, owner);
}
}
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
由此完成了bean实例对象的创建,然后会调用MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition方法。
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
2
3
4
5
6
7
8
9
10
11
12
AutowiredAnnotationBeanPostProcessor通过这个过程查找要@Autowired注入的方法、字段信息并保存下来
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
for (MergedBeanDefinitionPostProcessor processor : getBeanPostProcessorCache().mergedDefinition) {
processor.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
2
3
4
5
AutowiredAnnotationBeanPostProcessor的postProcessMergedBeanDefinition
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
metadata.checkConfigMembers(beanDefinition);
}
2
3
4
5
然后就进入到populateBean和initializeBean方法
// Initialize the bean instance.
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper);
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
2
3
4
5
6
# 实例化后处理
populateBean方法中,会先调用InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
2
3
4
5
6
7
然后调用InstantiationAwareBeanPostProcessor的postProcessProperties方法,可以做一些字段、方法的赋值调用,
PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Autowired字段、方法参数的注入就是在这里执行的,在AutowiredAnnotationBeanPostProcessor中。CommonAnnotationBeanPostProcessor 会处理@Resource注入。
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
try {
metadata.inject(bean, beanName, pvs);
}
catch (BeanCreationException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
}
return pvs;
}
2
3
4
5
6
7
8
9
10
11
12
13
# 初始化阶段
经过前面的步骤,bean实例创建完成、属性(比如@Autowired也赋值好了),下面进入初始化阶段(initialize)
initializeBean方法会先调用invokeAwareMethods,判断是否实现了BeanNameAware、BeanClassLoaderAware、BeanFactoryAware等接口并赋值。
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
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;
}
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
然后调用applyBeanPostProcessorsBeforeInitialization,也就是BeanPostProcessor的postProcessBeforeInitialization方法。
其中InitDestroyAnnotationBeanPostProcessor在这里调用@PostConstructor注解的方法。
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
try {
metadata.invokeInitMethods(bean, beanName);
}
catch (InvocationTargetException ex) {
throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Failed to invoke init method", ex);
}
return bean;
}
2
3
4
5
6
7
8
9
10
11
12
13
14
然后调用invokeInitMethods,判断如果bean实现了InitializingBean接口,调用afterPropertiesSet方法。
try {
invokeInitMethods(beanName, wrappedBean, mbd);
}
2
3
protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.hasAnyExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isTraceEnabled()) {
logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null && bean.getClass() != NullBean.class) {
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.hasAnyExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
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
最后调用applyBeanPostProcessorsAfterInitialization也就是BeanPostProcessor的postProcessAfterInitialization方法。
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
2
3
4
5
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
2
3
4
5
6
7
8
9
10
11
12
13
spring-aop就是通过这里给bean创建代理的,在
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
if (bean != null) {
Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
if (this.earlyProxyReferences.remove(cacheKey) != bean) {
return this.wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
2
3
4
5
6
7
8
9
10
# QA
- Q: spring bean创建完成字段的初始化是否保证happen before?比如@PostConstruct
A: @Autowired、@PostConstruct均执行在spring创建bean过程中,而spring创建singleton的bean时会加synchronized锁,从而实现@PostConstruct 执行happen before于 锁释放后的代码,也就是bean创建完成后使用的代码,能够保证可见性,不需要volatile标识。