(二):bean的生命周期

前言:记得20年年初在B站上看过Bean的生命周期的视频,最近实习到了尾期,想准备一下面试,就看了一下这部分的内容,发现网上博客各个版本都有,与之前看视频的讲解也是不一样的。所以只能自己看一下源码,做此笔记。

先理清下面两个单词吧

Instantiate: 实例化 ,java中表现为 new 构造方法 或 反射形式等…
Initialization:初始化 ,初始化就是给变量一个初始值

生命周期

Bean的生命周期总的来说只有四个。实例化,属性填充,初始化和销毁。

(二):bean的生命周期_第1张图片

BeanPostProcessor 及其子接口 InstantiationAwareBeanPostProcessor就是在这生命周期的不同阶段之间做增强的。

(二):bean的生命周期_第2张图片

AbstractAutowireCapableBeanFactory # createBean具体细分为下面的流程

(二):bean的生命周期_第3张图片

注意:有的Bean只需要经过 BeforeInstantiationpostProcessAfterInitialization 这两个处理点就可以直接到就绪状态,这个也是aop实现原理,后面会另开一篇写。

文字描述

BeanDefinition:bean的定义信息。

BeforeInstantiation:Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. 允许实现InstantiationAwareBeanPostProcessor接口的bean 通过postProcessBeforeInstantiation方法做特殊处理返回一个代理对象。

Instantiate:实例化bean

modify bean definition:允许MergedBeanDefinitionPostProcessor对bean定义信息修改。

AfterInstantiation:实例化后置增强。允许实现InstantiationAwareBeanPostProcessor接口的bean通过postProcessAfterInstantiation方法决定是否需要调用接口的postProcessProperties方法,若返回值为false,那么后续的postProcessProperties和图里的autowireapplyPropertyValues就直接跳过了。

autowire:根据BeanDefinitionautowireMode注入属性值。

applyPropertyValues:根据InstantiationAwareBeanPostProcessor接口的postProcessProperties返回值设置属性值。

invokeAwareMethods: 如果bean是一个BeanNameAware,调用其setBeanName;如果bean是一个BeanClassLoaderAware调用其setBeanClassLoader方法,如果bean是一个BeanFactoryAware,调用其setBeanFactory方法设置当前工厂。

postProcessBeforeInitialization:初始化前增强。允许BeanPostProcessor通过postProcessBeforeInitialization方法对bean进行增强。

invokeInitMethods:对于实现InitializingBean接口的bean,调用其afterPropertiesSet方法初始化bean。调用自定义的init方法。进行bean的初始化。

postProcessAfterInitialization:初始化后增强。允许BeanPostProcessor通过postProcessAfterInitialization方法对bean进行增强。

registerDisposableBean:如果是单例bean,往beanFactory的disposableBeans添加。注册bean的destroy方法。

从上面的文字描述可以看出 BeanPostProcessorInstantiationAwareBeanPostProcessor接口是对所有的bean的生效的,

Aware接口是对单个bean生效的。

源码分析

下面还是开始看源码吧。就按照第三张=图的流程来分析源码。

BeforeInstantiation

先看看AbstractAutowireCapableBeanFactory #createBean 方法

// 已删除无关代码
    protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
            throws BeanCreationException {
        
        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;
            }
        }
        
        Object beanInstance = doCreateBean(beanName, mbdToUse, args);
    
    }

resolveBeforeInstantiation方法对应是实例化之前阶段的代码,doCreateBean是后续实例化、初始化阶段。

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

先看看applyBeanPostProcessorsBeforeInstantiation代码做了什么

protected Object applyBeanPostProcessorsBeforeInstantiation(Class beanClass, String beanName) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
                if (result != null) {
                    return result;
                }
            }
        }
        return null;
    }

applyBeanPostProcessorsBeforeInstantiation先获取所有的BeanPostProcessor,然后调用遍历类型为·InstantiationAwareBeanPostProcessorBeanPostProcessorpostProcessBeforeInstantiation对beanClass进行处理,如果postProcessBeforeInstantiation的返回值不是null的话,直接返回该对象,否则返回null。

再看看postProcessBeforeInstantiation的方法描述:

Apply this BeanPostProcessor before the target bean gets instantiated. The returned bean object may be a proxy to use instead of the target bean, effectively suppressing default instantiation of the target bean.

在目标bean实例化之前应用这个BeanPospProcessor。返回的bean对象可以是一个代理,以代替目标bean,有效地抑制目标bean的默认实例化。

那么这一步的作用就是提供代理对象?

那么如果applyBeanPostProcessorsBeforeInstantiation返回值是一个对象,就会执行下面的applyBeanPostProcessorsAfterInitialization

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

这次遍历的是BeanPostProcessor调用其postProcessAfterInitialization方法,如果返回值不是null的话,直接返回该对象,否则返回null。

那么resolveBeforeInstantiation方法返回的值要么是一个对象要么是null。

再看看createBean的代码

        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;
            }
                Object beanInstance = doCreateBean(beanName, mbdToUse, args);
        }

如果返回值不是null的话,直接将这个对象作为bean返回。

否则就执行下面的doCreateBean方法,doCreateBean中主要代码是下面这些

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

        // Instantiate the bean.
    
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    
        // Allow post-processors to modify the merged bean definition.
        applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
            
        // Initialize the bean instance.
        Object exposedObject = bean;
        // 填充属性
        populateBean(beanName, mbd, instanceWrapper);
        // 初始化
        exposedObject = initializeBean(beanName, exposedObject, mbd);

        // Register bean as disposable.
        registerDisposableBeanIfNecessary(beanName, bean, mbd);

        return exposedObject;
    }

Instantiate

与此阶段对应的是createBeanInstance方法

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {

        // 如果存在工厂方法,使用工厂方法    
        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);
            }
        }

        // Candidate constructors for autowiring?
        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);
        }
        
        // 使用无参数构造
        // No special handling: simply use no-arg constructor.
        return instantiateBean(beanName, mbd);
    }

createBeanInstance中先判断bean实例化的形式并执行。有工厂方法,自动注入,默认构造方法,无参构造等多种形式的实例化。

modify bean definition

对应的是applyMergedBeanDefinitionPostProcessors方法

    protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class beanType, String beanName) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof MergedBeanDefinitionPostProcessor) {
                MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
                bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
            }
        }
    }

这个方法是遍历所有的MergedBeanDefinitionPostProcessor执行其postProcessMergedBeanDefinition方法,对bean的定义信息做修改增强。

AfterInstantiation

这个小阶段对应的是

@SuppressWarnings("deprecation")  // for postProcessPropertyValues
    protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
        boolean continueWithPropertyPopulation = true;
        // bean不是合成的且当前工厂有InstantiationAwareBeanPostProcessors
        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;
        }
}

遍历InstantiationAwareBeanPostProcessor,执行postProcessAfterInstantiation如果返回 e,退出循环。如果continueWithPropertyPopulation为false,退出populateBean方法。那么同样在 方法内的小阶段autowireapplyPropertyValues就不会被执行了,

看一下postProcessAfterInstantiation的方法描述

如果应在bean上设置属性,则为true;如果应跳过属性填充,则为false。正常的实现应该返回true。返回false还将阻止在此bean实例上调用任何后续实例化。

autowire

这个小阶段同样在populateBean方法内

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

autowire阶段根据AutowireMode的类型,获取需要自动注入的Bean 并与属性-值的形式存入PropertyValue中。

applyPropertyValues

        // 判断是否有InstantiationAwareBeanPostProcessors
        boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
        // 是否要check
        boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

        PropertyDescriptor[] filteredPds = null;
        if (hasInstAwareBpps) {
            if (pvs == null) {
                pvs = mbd.getPropertyValues();
            }
            //遍历InstantiationAwareBeanPostProcessor,执行postProcessProperties对PropertyDescriptor的值进行修改处理。
            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) {
            // 应用给定的属性值,解析对该bean工厂中其他bean的任何运行时引用。使用深拷贝
            applyPropertyValues(beanName, mbd, bw, pvs);
        }
autowireapplyPropertyValues阶段其实就是 属性填充这一生命周期,在此周期解析自动注入还有对自动注入值的增强。

invokeAwareMethods

invokeAwareMethods阶段代码是在initializeBean方法调用里的。

protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged((PrivilegedAction) () -> {
                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;        
    } 
 
    private void invokeAwareMethods(final String beanName, final Object bean) {
        // 判断bean是否是Aware接口
        if (bean instanceof Aware)
              // 应用相应的方法
            if (bean instanceof BeanNameAware) {
                ((BeanNameAware) bean).setBeanName(beanName);
            }
            if (bean instanceof BeanClassLoaderAware) {
                ClassLoader bcl = getBeanClassLoader();
                if (bcl != null) {
                    ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
                }
            }
            if (bean instanceof BeanFactoryAware) {
                ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
            }
        }
    }

invokeAwareMethods 阶段就就是执行Aware接口里的方法。

postProcessAfterInitialization

postProcessAfterInitialization阶段对应的是initializeBean方法里调用的applyBeanPostProcessorsBeforeInitialization方法

    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
            throws BeansException {

        Object result = existingBean;
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessBeforeInitialization(result, beanName);
            if (current == null) {
                return result;
            }
            result = current;
        }
        return result;
    }

applyBeanPostProcessorsBeforeInitialization方法遍历所有的BeanPostProcessor,调用其postProcessBeforeInitialization方法对bean进行增强。

invokeInitMethods

protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
            throws Throwable {
        // 如果是InitializingBean,调用其afterPropertiesSet方法
        boolean isInitializingBean = (bean instanceof InitializingBean);
        if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
            ....
            ((InitializingBean) bean).afterPropertiesSet();
            .....
            
        }
        
    // 如果存在自定义的Init方法,则调用
        if (mbd != null && bean.getClass() != NullBean.class) {
            String initMethodName = mbd.getInitMethodName();
            if (StringUtils.hasLength(initMethodName) &&
                    !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
                    !mbd.isExternallyManagedInitMethod(initMethodName)) {
                invokeCustomInitMethod(beanName, bean, mbd);
            }
        }
    }
// 删除了权限校验的代码    
protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd)
            throws Throwable {

        .....
         String initMethodName = mbd.getInitMethodName();
            // 反射调用init方法。
        final Method initMethod = (mbd.isNonPublicAccessAllowed() ?
            BeanUtils.findMethod(bean.getClass(), initMethodName) :
            ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));
        ......
            initMethod.invoke(bean), getAccessControlContext());

    }

invokeInitMethods阶段,先判断是否为InitializingBean,是的话调用afterPropertiesSet方法。然后如果存在自定义的Init方法的话,以反射的形式调用。

postProcessAfterInitialization

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

applyBeanPostProcessorsAfterInitialization方法遍历所有的BeanPostProcessor,调用其postProcessAfterInitialization方法对bean进行增强。

registerDisposableBean

    protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
        AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
        if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
            // 如果是单例
            if (mbd.isSingleton()) {
                // Register a DisposableBean implementation that performs all destruction
                // work for the given bean: DestructionAwareBeanPostProcessors,
                // DisposableBean interface, custom destroy method.
                // 添加的单例bean的map里面,使用DisposableBeanAdapter注册Destruction回调
                registerDisposableBean(beanName,
                        new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
            }
            else {
                // 向作用域map注册Destruction回调
                // A bean with a custom 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, getBeanPostProcessors(), acc));
            }
        }~~~~
    }

registerDisposableBeanIfNecessary 阶段就是根据bean作用域的不同,注册其解构的回调函数。

自此 bean已经处于就绪状态了,等到scope结束或者容器销毁,就执行其 destroy方法,销毁bean。
划分这么多小阶段只是为了分析源码时比较方便,而从spring原本的设计思想来看,生命周期应当是下面的这张图,此图引用于 https://www.jianshu.com/p/1de...

(二):bean的生命周期_第4张图片

你可能感兴趣的:(spring)