Spring's official website read the series (X): Spring Bean in the life cycle (lower)

 

Spring's official website read the series (nine): Spring Bean in the life cycle (lower)

 

The previous article, we have to Bean's life cycle to do a brief introduction, describes the initialization phase of the lifecycle and the container start and stop based callback mechanism LifeCycleBean, in addition to the destruction process Bean also made a brief introduction . But Bean for the entire life cycle, this is just a small part, in this article, we will learn to complete the remaining part of the study, while the previous contents do a review. Bean's entire life cycle, in accordance with our previous presentation, can be divided into four parts

Examples of attribute initialization destruction injection

This paper describes the injection phase and attributes instantiated

Life Cycle concept of complementarity

Although we have always said Bean entire life cycle is divided into four parts, but I believe that many students have been in the end where to start to Bean's life cycle, where the end is not a clear concept. You might say, not that instantiated from the beginning to the end to destroy it? Of course, this is not wrong, but exactly when operators begin to instantiate it? When they count destroy it? The question whether or not you can clearly answer it? If not, please continue to read.

I believe that the entire Spring Bean in the life cycle, from the first call applyBeanPostProcessorsBeforeInstantiation method postprocessor in the beginning, this method is intended to see to know the name, which translates to call postprocessor before instantiated. The call applyBeanPostProcessorsAfterInitialization method, the end stage of the life cycle means that Bean was created. For the destruction of no ambiguity, that is, call the corresponding methods of destruction Bean Bean would think that with this life came to an end, marking the end of Bean lifecycle. Then combined with the conclusions of the previous article, I now range Bean's life cycle defined as follows:

Spring's official website read the series (nine): Spring Bean in the life cycle (lower)

 

Note that, for BeanDefinion scanning, parsing, validation is not part of Bean's life cycle. Such a clear definition of the concept of life-cycle Bean is necessary, perhaps just beginning for us, Bean's life cycle is a mess, but at least now we have caught thread. Bean while the entire life cycle, I will be divided into two parts

  • create
  • destroy

For the period of destruction, we do not need too much attention, for the creation phase, signs began to behave as: applyBeanPostProcessorsBeforeInstantiation method of execution, marked the end of behavior: applyBeanPostProcessorsAfterInitialization method is executed.

Based on the above conclusion, we begin the next analysis for analysis of code in this article, we refer to the following chart

Spring's official website read the series (nine): Spring Bean in the life cycle (lower)

 

Instantiation

Examples of the entire process for the main image above 3-11-6-4 (createBean) and 3-11-6-4-1 (doCreateBean) Step

createBean process analysis

code show as below:

protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {

RootBeanDefinition mbdToUse = mbd;

// 第一步:解析BeanDefinition中的beanClass属性
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}

try {
// 第二步:处理lookup-method跟replace-method,判断是否存在方法的重载
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}

try {
// 第三步:判断这个类在之后是否需要进行AOP代理
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);
}

try {
// 开始创建Bean
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}

Can be seen, with the first step or the second step in the process of doing BeanDefinition some of the property, which is not part of our Bean's life cycle, we skip, then look at the third step of the code:

protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// 不是合成类,并且有实例化后置处理器。这个判断基本上恒成立
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
// 获取这个BeanDefinition的类型
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
// 这里执行的主要是AbstractAutoProxyCreator这个类中的方法,决定是否要进行AOP代理
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
// 这里执行了一个短路操作,如果在这个后置处理中直接返回了一个Bean,那么后面相关的操作就不会执行了,只会执行一个AOP的代理操作
if (bean != null) {
// 虽然这个Bean被短路了,意味着不需要经过后面的初始化阶段,但是如果需要代理的话,还是要进行AOP代理,这个地方的短路操作只是意味着我们直接在后置处理器中提供了一个准备充分的的Bean,这个Bean不需要进行初始化,但需不需要进行代理,任然由AbstractAutoProxyCreator的applyBeanPostProcessorsBeforeInstantiation方法决定。在这个地方还是要调用一次Bean的初始化后置处理器保证Bean被完全的处理完
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
// bean != null基本会一直返回false,所以beforeInstantiationResolved这个变量也会一直为false
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}

For AbstractAutoProxyCreator in applyBeanPostProcessorsBeforeInstantiation this method of analysis Leave aside until AOP conducting a detailed analysis of the learning phase. Let us just need to know that this method will decide whether or not to generate a proxy object for this follow-up in Bean.

doCreateBean process analysis

    protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {

BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
// 第一步:单例情况下,看factoryBeanInstanceCache这个缓存中是否有
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 第二步:这里创建对象
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}

synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
// 第三步:后置处理器处理
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
// 省略异常处理
}
mbd.postProcessed = true;
}
}

// 循环引用相关,源码阅读阶段再来解读这段代码,暂且就关注以下后置处理器的调用时机
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
// 第四步:调用后置处理器,早期曝光一个工厂对象
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}

Object exposedObject = bean;
try {
// 第五步:属性注入
populateBean(beanName, mbd, instanceWrapper);
// 第六步:初始化
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
// 省略异常处理
}
}

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<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
// 省略异常处理
}
}
}
}

try {
// 第七步:注册需要销毁的Bean,放到一个需要销毁的Map中(disposableBeans)
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
// 省略异常处理
}

return exposedObject;
}

The first step: When factoryBeanInstanceCache is not empty?

if (mbd.isSingleton()) {
// 第一步:单例情况下,看factoryBeanInstanceCache这个缓存中是否有
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}

This code is very complicated to go into, I am here to simply use the next theory to explain:

Suppose we now have a IndexService, it has a property A, the following code:

@Component
public class IndexService {
@Autowired
A a;

public A getA() {
return a;
}
}

And this is the form FactroyBean A configuration, as follows:

@Component
public class MyFactoryBean implements SmartFactoryBean {
@Override
public A getObject() throws Exception {
return new A();
}
@Override
public Class<?> getObjectType() {
return A.class;
}
// 这个地方并不一定要配置成懒加载,这里只是为了让MyFactoryBean这个Bean在IndexService之后实例化
@Override
public boolean isEagerInit() {
return false;
}
}

We think about a problem at the top of this scenario, when IndexService To complete the property injection, Spring how would you do it?

Spring now know IndexService to inject a property of type A, so it will be parsed through all of BeanDefinition, then each BeanDefinition the type is not the type A, similar to the following:

for (String beanName : this.beanDefinitionNames) {
// 1.获取BeanDefinition
// 2.根据BeanDefinition中的定义判断是否是一个A
}

Such judgments in most cases above is true, but for a special Bean is not enough that we introduced earlier FactoryBean, because our purpose is not configured FactoacryBean directly FactoryBean the Bean itself, but want through its getObject method will object into a Spring container, so when we traversed a BeanDefinition, and this is a FactoacryBean BeanDefinition when you need to do special treatment, we know that there is a getObjectType FactoacryBean method, we can get through this method this type of object to be created FactoacryBean, if we can call this method, then since we can not determine whether this is a type a a.

However, in our example above, this time MyFactoryBean has not yet been created. Therefore, at this time will go Spring instantiate MyFactoryBean, then call its methods getObjectType, do determine the type, attribute and finally injection, the following pseudo-code:

for (String beanName : this.beanDefinitionNames) {
// 1.获取BeanDefinition
// 2.如果不是一个FactoacryBean,直接根据BeanDefinition中的属性判断
if(不是一个FactoacryBean){
//直接根据BeanDefinition中的属性判断是不是A
}
// 3.如果是一个FactoacryBean
if(是一个FactoacryBean){
// 先创建这个FactoacryBean,然后再调用getObjectType方法了
}
}

We can according to our own debugging the code above, I am here to hold a screenshot of debug.

Step 2: Create Object (createBeanInstance)

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// 获取到解析后的beanClass
Class<?> beanClass = resolveBeanClass(mbd, beanName);

// 忽略异常处理
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}

// 获取工厂方法,用于之后创建对象
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}

// 原型情况下避免多次解析
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);
}
}

// 跟后置处理器相关,我们主要关注这行代码
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}

// Preferred constructors for default construction?
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}

// 默认使用无参构造函数创建对象
return instantiateBean(beanName, mbd);
}

When an object is created, the rest of the code we do not do too much attention. Let us know in the process of object creation, Spring will call a post-processor to infer the constructor.

The third step: applyMergedBeanDefinitionPostProcessors

BeanDefinition after the merger application, Spring themselves use this to do some caching annotation metadata.

We AutowiredAnnotationBeanPostProcessor corresponding method of this class look about its role

public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
// 这个方法就是找到这个正在创建的Bean中需要注入的字段,并放入缓存中
InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
metadata.checkConfigMembers(beanDefinition);
}

Step Four: getEarlyBeanReference

protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
// 在这里保证注入的对象是一个代理的对象(如果需要代理的话),主要用于循环依赖
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
}
}
}
return exposedObject;
}

Properties injection

Step five: Properties injection (populateBean)

    protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
if (bw == null) {
if (mbd.hasPropertyValues()) {
// 省略异常
}
else {
return;
}
}

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;
}

PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

// 自动注入模型下,找到合适的属性,在后续方法中再进行注入
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}

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

PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 精确注入下,在这里完成属性注入
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
// 一般不会进行这个方法
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
}
if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
checkDependencies(beanName, mbd, filteredPds, pvs);
}

if (pvs != null) {
// XML配置,或者自动注入,会将之前找到的属性在这里进行注入
applyPropertyValues(beanName, mbd, bw, pvs);
}
}

Throughout the process above, we have focused on a method, postProcessProperties, injection point found by the postProcessMergedBeanDefinition method, injection method at this point before this will. Upon completion of the injection property, they began initialized, the initialization process in the last article has been introduced, will not repeat them here.

to sum up

In these two articles, we have all of Bean's life cycle to do a detailed analysis, of course, for some complex code, yet without questioning, because after going to write a series of articles dedicated source code analysis. We can focus on my follow-up article. Bean for the entire life cycle of the drawing can be summarized as follows

Spring's official website read the series (nine): Spring Bean in the life cycle (lower)

 

First of all, the entire life cycle of our Bean can be divided into two parts

  1. create
  2. destroy

For the creation phase, we are in turn divided into three steps

  • Instantiation
  • Properties injection
  • initialization

We can see that in the whole process BeanPostPorcessor interspersed execution, assisted Spring Bean completed the entire life cycle.

 


Recommended Reading

Spring's official website read the series (a): Spring container and instantiated

Spring's official website read the series (B): Spring dependency injection and injection method

Spring's official website read the series (three): automatically injected with precise injection

Guess you like

Origin www.cnblogs.com/Java3272858604/p/12583880.html