关于spring:二bean的生命周期

43次阅读

共计 14753 个字符,预计需要花费 37 分钟才能阅读完成。

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

先理清上面两个单词吧

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

生命周期

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

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

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

留神:有的 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<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;        
    }
    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…。

正文完
 0