关于spring:二bean的生命周期

前言:记得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…。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理