spring bean生命周期源码解析-JDK17

一、整体流程
实例化
属性注入
初始化
销毁
二、createBeanInstance
1、supplier创建对象
2、工厂方法创建对象
3、根据构造方法通过反射创造对象
默认的构造函数 or 注入的构造函数

private int autowireMode;
public static final int AUTOWIRE_NO = 0;
public static final int AUTOWIRE_BY_NAME = 1;
public static final int AUTOWIRE_BY_TYPE = 2;
public static final int AUTOWIRE_CONSTRUCTOR = 3;
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized(mbd.constructorArgumentLock) {
	//使用过的构造方法 (缓存)或者 FactoryMethod 不为空 
	if (mbd.resolvedConstructorOrFactoryMethod != null) {
		//1.此处 resolved = true;
		resolved = true;
		//2.构造方法 是否 使用了参数注入
		autowireNecessary = mbd.constructorArgumentsResolved;
		}
	}
}
//存在缓存
  if (resolved) {
//使用了参数注入, 用有参的构造方法 来 创建bean。会从beanDefinition里取出 缓存的构造方法和 参数列表 直接反射这个方法,创建对象。没有使用参数注入, 走无参构造方法。 反射无参构造方法。
//autowireConstructor(beanName, mbd, null, null) : 用有参的 构造方法 创建对象。
//instantiateBean(beanName, mbd) :用无参构造方法 创建对象。
             return autowireNecessary ? this.autowireConstructor(beanName, mbd, (Constructor[])null, (Object[])null) : this.instantiateBean(beanName, mbd);
                } else {
//单例Bean 第一次创建对象, 肯定是 不存在缓存的,需要自己选择合适的构造器。
                    Constructor<?>[] ctors = this.determineConstructorsFromBeanPostProcessors(beanClass, beanName);
//构造参数为空
//注入方式不为构造器注入 
//mbd.hasConstructorArgumentValues()的值不为空,因此会使用带参数的构造器注入。
//不存在 bean 定义的构造函数参数值;
//用于构造函数或工厂方法调用的显式参数为空;
                    if (ctors == null && mbd.getResolvedAutowireMode() != 3 && !mbd.hasConstructorArgumentValues() && ObjectUtils.isEmpty(args)) {
                        //首选默认的构造方式
                        ctors = mbd.getPreferredConstructors();
                        //instantiateBean 用默认的构造方法进行bean的实例化
                        //autowireConstructor 构造函数自动注入
                        return ctors != null ? this.autowireConstructor(beanName, mbd, ctors, (Object[])null) : this.instantiateBean(beanName, mbd);
                    } else {
                        //构造函数自动注入
                        return this.autowireConstructor(beanName, mbd, ctors, args);
                    }
                }

三、populateBean

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
        //针对 bean 的包装器是否为空
        //是否存在为此 bean 定义的属性值,做不同的处理
        if (bw == null) 
        {
        //如果 bean 的包装器为空,但是又存在为此 bean 定义的属性值,Spring 则会抛出 BeanCreationException 异常
        //因为属性填充就是要给 BeanWrapper 中的 bean 实例中的属性进行赋值的过程,存在属性,但是 BeanWrapper 为空,也就是 BeanWrapper                
        //中的 bean 实例为空,那么显然不行
            if (mbd.hasPropertyValues()) 
            {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
            }
        } else 
        {
        // InstantiationAwareBeanPostProcessor后置处理器:可以在属性设置前修改bean
        //如果 bean 定义不是合成的,并且工厂中存在创建时应用于单例 bean 的 InstantiationAwareBeanPostProcessor 后置处理器,则需要处
        //理执行它的 postProcessAfterInstantiation() 方法
            if (!mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) {
                //获取到 bean 工厂所有已经注册的 BeanPostProcessor
                Iterator var4 = this.getBeanPostProcessorCache().instantiationAware.iterator();
                while(var4.hasNext()) {
                    InstantiationAwareBeanPostProcessor bp = (InstantiationAwareBeanPostProcessor)var4.next();
                    
                //如果类型匹配的话,将会执行 InstantiationAwareBeanPostProcessor 的 postProcessAfterInstantiation() 方法
                //postProcessAfterInstantiation() 方法:在 bean 实例化后,属性填充之前被调用,允许修改 bean 的属性,默认实现是返回 
                //true
                    if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                    //如果postProcessAfterInstantiation() 方法返回 false,则跳过后面的属性填充过程
                    //why???
                        return;
                    }
                }
            }
            //获取到 bean 定义中封装好的属性值
            PropertyValues pvs = mbd.hasPropertyValues() ? mbd.getPropertyValues() : null;
            //根据设置的自动注入方式(名称或者类型)获取属性 bean(递归getBean)存入 PropertyValues 中
            int resolvedAutowireMode = mbd.getResolvedAutowireMode();
            if (resolvedAutowireMode == 1 || resolvedAutowireMode == 2) {
                MutablePropertyValues newPvs = new MutablePropertyValues((PropertyValues)pvs);
                //根据名称自动注入
                if (resolvedAutowireMode == 1) {
                    this.autowireByName(beanName, mbd, bw, newPvs);
                }
                //根据类型自动注入
                if (resolvedAutowireMode == 2) {
                    this.autowireByType(beanName, mbd, bw, newPvs);
                }

                pvs = newPvs;
            }
            // hasInstAwareBpps:工厂是否存在将在创建时应用于单例 bean 的 InstantiationAwareBeanPostProcessor后置处理器
            boolean hasInstAwareBpps = this.hasInstantiationAwareBeanPostProcessors();
            // needsDepCheck:是否需要进行依赖检查
            boolean needsDepCheck = mbd.getDependencyCheck() != 0;
            PropertyDescriptor[] filteredPds = null;
            
            //如果存在 InstantiationAwareBeanPostProcessor 后置处理器,需要执行 InstantiationAwareBeanPostProcessor 的
            //postProcessProperties() 以及 postProcessPropertyValues() 方法回调
            if (hasInstAwareBpps) {
                if (pvs == null) {
                    pvs = mbd.getPropertyValues();
                }
                PropertyValues pvsToUse;
        //执行 InstantiationAwareBeanPostProcessor 的 postProcessProperties() 以及postProcessPropertyValues() 方法回调
        //postProcessProperties(): 允许对填充前的属性进行处理(如对属性的验证)
        //postProcessPropertyValues(): 对属性值进行修改,通过基于原始的 PropertyValues 创建一个新的MutablePropertyValues 实例,       
        //添加或删除特定的值。
        //不过目前方法已经被标记为过期,在后续 Spring 版本中可能会被删除
                for(Iterator var9 = this.getBeanPostProcessorCache().instantiationAware.iterator(); var9.hasNext(); pvs = pvsToUse) {
                    InstantiationAwareBeanPostProcessor bp = (InstantiationAwareBeanPostProcessor)var9.next();
                    pvsToUse = bp.postProcessProperties((PropertyValues)pvs, bw.getWrappedInstance(), beanName);
                    if (pvsToUse == null) {
                        if (filteredPds == null) {
                            filteredPds = this.filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                        }

                        pvsToUse = bp.postProcessPropertyValues((PropertyValues)pvs, filteredPds, bw.getWrappedInstance(), beanName);
                        if (pvsToUse == null) {
                            return;
                        }
                    }
                }
            }
            //执行依赖检查,对应 depend-on 属性
            if (needsDepCheck) {
                if (filteredPds == null) {
                    filteredPds = this.filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                }
                //依赖检查,对应 depend-on 属性
                this.checkDependencies(beanName, mbd, filteredPds, (PropertyValues)pvs);
            }
            //属性填充的具体过程,即将属性值赋值到 beanWrapper 中 bean 实例的具体属性中
            if (pvs != null) {
                //开始填充属性值
                //!!!!!!
                this.applyPropertyValues(beanName, mbd, bw, (PropertyValues)pvs);
            }
        }
    }

四、initializeBean

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged(() -> {
                //1、执行Aware方法,如 BeanNameAware、BeanClassLoaderAware、BeanFactoryAware
                this.invokeAwareMethods(beanName, bean);
                return null;
            }, this.getAccessControlContext());
        } else {
            //1、执行Aware方法,如 BeanNameAware、BeanClassLoaderAware、BeanFactoryAware
            this.invokeAwareMethods(beanName, bean);
        }
        //调用 BeanPostProcessor 的前置处理
        Object wrappedBean = bean;
        if (mbd == null || !mbd.isSynthetic()) {
        //执行 BeanPostProcessor 后置处理器的前置处理方法:postProcessBeforeInitialization(),允许对bean实例进行包装
            wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName);
        }
        try {
            //执行初始化方法,包括 InitializingBean 的 afterPropertiesSet() 方法、自定义的初始化方法 init-method
            this.invokeInitMethods(beanName, wrappedBean, mbd);
        } catch (Throwable var6) {
            throw new BeanCreationException(mbd != null ? mbd.getResourceDescription() : null, beanName, "Invocation of init method failed", var6);
        }

        if (mbd == null || !mbd.isSynthetic()) {
            //执行 BeanPostProcessor 后置处理器的后置处理方法:postProcessAfterInitialization(),允许对 bean 实例进行包装
            wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        }

        return wrappedBean;
    }
private void invokeAwareMethods(String beanName, Object bean) {
        if (bean instanceof Aware) {
            //如果 bean 实现了 BeanNameAware 接口,则设置 BeanName
            if (bean instanceof BeanNameAware) {
                ((BeanNameAware)bean).setBeanName(beanName);
            }
            //如果 bean 实现了 BeanClassLoaderAware 接口,则设置 BeanClassLoader
            if (bean instanceof BeanClassLoaderAware) {
                ClassLoader bcl = this.getBeanClassLoader();
                if (bcl != null) {
                    ((BeanClassLoaderAware)bean).setBeanClassLoader(bcl);
                }
            }
            //如果 bean 实现了 BeanFactoryAware 接口,则设置 BeanFactory
            if (bean instanceof BeanFactoryAware) {
                ((BeanFactoryAware)bean).setBeanFactory(this);
            }
        }

    }
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;

        Object current;
        //获取所有的 BeanPostProcessor 进行遍历 迭代器
        for(Iterator var4 = this.getBeanPostProcessors().iterator(); var4.hasNext(); result = current) {
            BeanPostProcessor processor = (BeanPostProcessor)var4.next();
            //执行每一个 BeanPostProcessor 的前置增强方法:postProcessBeforeInitialization()
            current = processor.postProcessBeforeInitialization(result, beanName);
            if (current == null) {
                return result;
            }
        }
        return result;
    }
protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd) throws Throwable {
    //检查 bean 是否实现了 InitializingBean 接口,如果实现了,则需要执行 InitializingBean 接口的 afterPropertiesSet() 方法
        boolean isInitializingBean = bean instanceof InitializingBean;
        if (isInitializingBean && (mbd == null || !mbd.hasAnyExternallyManagedInitMethod("afterPropertiesSet"))) {
            if (this.logger.isTraceEnabled()) {
                this.logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
            }
            //调用 InitializingBean 接口的 afterPropertiesSet() 方法
            if (System.getSecurityManager() != null) {
                try {
                    AccessController.doPrivileged(() -> {
                        ((InitializingBean)bean).afterPropertiesSet();
                        return null;
                    }, this.getAccessControlContext());
                } catch (PrivilegedActionException var6) {
                    throw var6.getException();
                }
            } else {
            //直接调用 InitializingBean 接口中的 afterPropertiesSet 方法
                ((InitializingBean)bean).afterPropertiesSet();
            }
        }
        //调用xml 中声明的 init-method 指定的方法
        if (mbd != null && bean.getClass() != NullBean.class) {
        //判断是否指定了 init-method 方法,如果指定了 init-method 方法,则再调用制定的 init-method
            String initMethodName = mbd.getInitMethodName();
            if (StringUtils.hasLength(initMethodName) && (!isInitializingBean || !"afterPropertiesSet".equals(initMethodName)) && !mbd.hasAnyExternallyManagedInitMethod(initMethodName)) {
                //进入该方法可知通过反射的方式调用 init-method 方法
                this.invokeCustomInitMethod(beanName, bean, mbd);
            }
        }

    }

五、调用DisposableBean 接口的 destroy 方法

protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
        AccessControlContext acc = System.getSecurityManager() != null ? this.getAccessControlContext() : null;
        //如果 Bean 不是多例且需要在容器关闭时销毁
        if (!mbd.isPrototype() && this.requiresDestruction(bean, mbd)) {
        // 如果 bean 的作用域是 singleton,则会注册用于销毁的 bean 到 disposableBeans 缓存,执行给定 bean 的所有销毁工作
            if (mbd.isSingleton()) {
                //给当前Bean绑定一个DisposableBeanAdapter
                this.registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, mbd, this.getBeanPostProcessorCache().destructionAware, acc));
            } else {
        //如果 bean 的作用域不是 prototype,也不是 singleton,而是其他作自定义用域的话,则注册一个回调,以在销毁作用域内的指定对象时执行
                Scope scope = (Scope)this.scopes.get(mbd.getScope());
                if (scope == null) {
                    throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
                }

                scope.registerDestructionCallback(beanName, new DisposableBeanAdapter(bean, beanName, mbd, this.getBeanPostProcessorCache().destructionAware, acc));
            }
        }

    }

public void registerDisposableBean(String beanName, DisposableBean bean) {
    // 注册用于销毁的 bean 到 disposableBeans 的 map 中,以供后续使用
    synchronized (this.disposableBeans) {
        this.disposableBeans.put(beanName, bean);
    }
}

销毁具体调用步骤可参见下面这篇博客
https://blog.csdn.net/wuhuayangs/article/details/122533793
六、总结
实例化(构造函数):createBeanInstance
属性注入:populateBean
初始化:initializeBean
1、执行Aware方法,如 BeanNameAware、BeanFactoryAware、BeanClassLoaderAware
2、调用 BeanPostProcessor 的前置处理,postProcessBeforeInitialization(),对bean实例进行包装
3、实现了initializingBean接口,调用了afterPropertiesSet()方法
4、调用 BeanPostProcessor 的后置处理,postProcessAfterInitialization()
销毁:调用DisposableBean 接口的 destroy 方法

  • 11
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值