Spring boot bean 的生命周期

很多文章認(rèn)為Bean 的生命周期分為四步

  • 實(shí)例化 Instantiation
  • 屬性賦值 Populate
  • 初始化 Initialization
  • 銷毀 Destruction

但是從我個(gè)人認(rèn)為,這個(gè)分法是不完整的。少了一個(gè)Metadata 的構(gòu)建過程,任何一個(gè)bean 不是天生就有的,而且在BeanFactory 里獲得它的metadata BeanDefinition(里面包含了各種bean的基本信息,比如name, 依賴等等), 沒有這一步,無從談起下一步。所以我更喜歡下面一張圖。

image.png

一個(gè)app 的bean 的結(jié)構(gòu)關(guān)系,可以用一個(gè)DAG 來描述。在這個(gè)DAG 中,有顯示的依賴關(guān)系,有隱式的依賴關(guān)系。依賴意味著順序, 因此在描述所有的Bean的時(shí)候,實(shí)際上還要描述Bean的構(gòu)造順序。 比如@AutoConfigureOrder annotation 或者Ordered 之類的接口存在,來描述他們之間的先后關(guān)系。

保證所有的Bean 能夠按照順序來進(jìn)行執(zhí)行是非常重要的,否則在spring 升級(jí),或者系統(tǒng)升級(jí)后出現(xiàn)各種各樣的問題。在單個(gè)bean 的生命周期上,從實(shí)例化是沒錯(cuò)的。但是如果放在整個(gè)app,忽略metadata 的構(gòu)建的順序和過程是不可以的,尤其是在spring 的基礎(chǔ)上再次開發(fā),提供平臺(tái)的用戶來說。這是必須要掌握的內(nèi)容。

這是BeanFactory的創(chuàng)建和銷毀bean的流程。


image.png

創(chuàng)建時(shí)機(jī)

我們可以在Spring應(yīng)用上下文初始化時(shí)或者我們自己創(chuàng)建BeanFactory去實(shí)例化bean。

Spring應(yīng)用上下文在invokeBeanFactoryPostProcessors、finishBeanFactoryInitialization等階段會(huì)實(shí)例化bean。
事實(shí)上當(dāng)通過BeanFactory的getBean()方法來請(qǐng)求對(duì)象實(shí)例時(shí), 才有可能觸發(fā)Bean實(shí)例化階段的活動(dòng)。

一些概念:

RequiredAnnotationBeanPostProcessor 是處理@Required注解的邏輯
AutowiredAnnotationBeanPostProcessor 是處理@Autowired和@Value和@javax.inject.Inject
CommonAnnotationBeanPostProcessor jsr250注解如javax.annotation.Resource、@PreDestroy、@PostConstruct的處理

銷毀時(shí)機(jī)

在beanFactory創(chuàng)建bean時(shí),最后會(huì)調(diào)用registerDisposableBeanIfNecessary方法。

單例bean 會(huì)在Spring應(yīng)用正常結(jié)束時(shí)被shutdownhook或手動(dòng)調(diào)用beanFactory的destroySingletons方法去銷毀。
自定義Scope的bean 需要自實(shí)現(xiàn)registerDestructionCallback方法,將DisposableBeanAdapter按照自己的邏輯自行銷毀。
prototype bean spring沒有提供銷毀邏輯。我們可以通過自實(shí)現(xiàn)一個(gè)BeanPostProcessor去實(shí)現(xiàn)(即通過單例的BeanPostProcessor會(huì)在初始化階段收集prototype bean,銷毀則跟隨destroySingletons方法觸發(fā)自實(shí)現(xiàn)銷毀)。

拓展點(diǎn)

InstantiationAwareBeanPostProcessor 感知Bean實(shí)例化的處理器
MergedBeanDefinitionPostProcessor 對(duì)merged beanDefinition進(jìn)行處理
BeanNameAware、BeanClassLoaderAware、BeanFactoryAware bean可實(shí)現(xiàn)這些接口獲取對(duì)應(yīng)資源
BeanPostProcessor 可以新bean實(shí)例化前后做一些自定義操作。
InitializingBean、DisposableBean、initMethod、destroyMethod 提供給bean的初始化和銷毀的感知處理
BeanDefinitionRegistryPostProcessor 可用于增加額外beanDefinition,在Spring上下文refresh的invokeBeanFactoryPostProcessors時(shí)調(diào)用。
SmartInitializingSingleton接口 在所有單例bean都被初始化完成后回調(diào)執(zhí)行, 以便在常規(guī)實(shí)例化后執(zhí)行一些初始化,避免意外的早期初始化帶來的副作用(例如,來自ListableBeanFactory.getBeansOfType調(diào)用),懶加載的bean不能觸發(fā)執(zhí)行

源碼分析


    /**
     * 完成bean工廠的初始化
     * 實(shí)例化所有的單例(非懶惰)bean
     */
    protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
        // Initialize conversion service for this context.
        // 1.初始化conversionService
        if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
                beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
            beanFactory.setConversionService(
                    beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
        }

        // 2.Register a default embedded value resolver if no bean post-processor
        // (such as a PropertyPlaceholderConfigurer bean) registered any before:
        // at this point, primarily for resolution in annotation attribute values.
        if (!beanFactory.hasEmbeddedValueResolver()) {
            beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
        }

        // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
        // 3.初始化LoadTimeWeaverAware,使得盡早進(jìn)行注冊(cè)transformer(運(yùn)行期織入)
        String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
        for (String weaverAwareName : weaverAwareNames) {
            getBean(weaverAwareName);
        }

        // 4.Stop using the temporary ClassLoader for type matching.
        beanFactory.setTempClassLoader(null);

        // 5.Allow for caching all bean definition metadata, not expecting further changes.
        beanFactory.freezeConfiguration();

        // Instantiate all remaining (non-lazy-init) singletons.
        // 6.初始化所有非懶惰的bean
        beanFactory.preInstantiateSingletons();
    }

    public void preInstantiateSingletons() throws BeansException {
        if (logger.isTraceEnabled()) {
            logger.trace("Pre-instantiating singletons in " + this);
        }

        // Iterate over a copy to allow for init methods which in turn register new bean definitions.
        // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
        List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

        // 3.1Trigger initialization of all non-lazy singleton beans...
        for (String beanName : beanNames) {
            // 3.2獲取bean的合并的beandefinition
            RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
            if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
                //3.3判斷是否工廠bean
                if (isFactoryBean(beanName)) {
                    Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
                    if (bean instanceof FactoryBean) {
                        final FactoryBean<?> factory = (FactoryBean<?>) bean;
                        boolean isEagerInit;
                        if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                            isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
                                            ((SmartFactoryBean<?>) factory)::isEagerInit,
                                    getAccessControlContext());
                        }
                        else {
                            isEagerInit = (factory instanceof SmartFactoryBean &&
                                    ((SmartFactoryBean<?>) factory).isEagerInit());
                        }
                        if (isEagerInit) {
                            getBean(beanName);
                        }
                    }
                }
                else {
                    //3.4getBean
                    getBean(beanName);
                }
            }
        }

        // Trigger post-initialization callback for all applicable beans...
        // 3.5為實(shí)現(xiàn)了SmartInitializingSingleton的bean執(zhí)行afterSingletonsInstantiated方法
        for (String beanName : beanNames) {
            Object singletonInstance = getSingleton(beanName);
            if (singletonInstance instanceof SmartInitializingSingleton) {
                final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
                if (System.getSecurityManager() != null) {
                    Access Controller.doPrivileged((PrivilegedAction<Object>) () -> {
                        smartSingleton.afterSingletonsInstantiated();
                        return null;
                    }, getAccessControlContext());
                }
                else {
                    //3.6 smartSingleton.afterSingletonsInstantiated();
                }
            }
        }
    }

我們重點(diǎn)看3.4步getBean方法, 事實(shí)上當(dāng)通過BeanFactory的getBean()方法來請(qǐng)求對(duì)象實(shí)例時(shí), 才有可能觸發(fā)Bean實(shí)例化階段的活動(dòng)。
注:在前面應(yīng)用上下文的啟動(dòng)階段,某些bean(如BeanFactoryPostProcessor)已經(jīng)通過調(diào)用調(diào)用該方法實(shí)例化過了。

    //AbstractBeanFactory
    @Override
    public Object getBean(String name) throws BeansException {
        return doGetBean(name, null, null, false);
    }

    //AbstractBeanFactory.doGetBean
    protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
            @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
        //3.4.1轉(zhuǎn)換成準(zhǔn)確的bean name,去除beanfactory bean的&前綴,獲取別名map中真名。
        final String beanName = transformedBeanName(name);
        Object bean;

        // Eagerly check singleton cache for manually registered singletons.
        // 3.4.2查找那些已經(jīng)通過手動(dòng)注冊(cè)了的bean
        Object sharedInstance = getSingleton(beanName);
        if (sharedInstance != null && args == null) {
            if (logger.isTraceEnabled()) {
                if (isSingletonCurrentlyInCreation(beanName)) {
                    logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
                            "' that is not fully initialized yet - a consequence of a circular reference");
                }
                else {
                    logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
                }
            }
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
        }

        else {
            //3.4.3 Fail if we're already creating this bean instance:
            // We're assumably within a circular reference.
            if (isPrototypeCurrentlyInCreation(beanName)) {
                throw new BeanCurrentlyInCreationException(beanName);
            }

            //3.4.4 查看父beanFactory是否含有該bean的bean definition
            BeanFactory parentBeanFactory = getParentBeanFactory();
            if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
                // Not found -> check parent.
                String nameToLookup = originalBeanName(name);
                if (parentBeanFactory instanceof AbstractBeanFactory) {
                    return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
                            nameToLookup, requiredType, args, typeCheckOnly);
                }
                else if (args != null) {
                    // Delegation to parent with explicit args.
                    return (T) parentBeanFactory.getBean(nameToLookup, args);
                }
                else if (requiredType != null) {
                    // No args -> delegate to standard getBean method.
                    return parentBeanFactory.getBean(nameToLookup, requiredType);
                }
                else {
                    return (T) parentBeanFactory.getBean(nameToLookup);
                }
            }

            if (!typeCheckOnly) {
                markBeanAsCreated(beanName);
            }

            try {
                final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                checkMergedBeanDefinition(mbd, beanName, args);

                // Guarantee initialization of beans that the current bean depends on.
                // 3.4.5保證當(dāng)前beanname聲明的@DependsOn或xml的depends-on類的初始化
                String[] dependsOn = mbd.getDependsOn();
                if (dependsOn != null) {
                    for (String dep : dependsOn) {
                        if (isDependent(beanName, dep)) {
                            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                        }
                        registerDependentBean(dep, beanName);
                        try {
                            getBean(dep);
                        }
                        catch (NoSuchBeanDefinitionException ex) {
                            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                        }
                    }
                }

                // Create bean instance.
                // 3.4.6 創(chuàng)建單例bean
                if (mbd.isSingleton()) {
                    // 3.4.6 創(chuàng)建單例bean
                    sharedInstance = getSingleton(beanName, () -> {
                        try {
                            return createBean(beanName, mbd, args);
                        }
                        catch (BeansException ex) {
                            // Explicitly remove instance from singleton cache: It might have been put there
                            // eagerly by the creation process, to allow for circular reference resolution.
                            // Also remove any beans that received a temporary reference to the bean.
                            destroySingleton(beanName);
                            throw ex;
                        }
                    });
                    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                }

                else if (mbd.isPrototype()) {
                    // It's a prototype -> create a new instance.
                    Object prototypeInstance = null;
                    try {
                        beforePrototypeCreation(beanName);
                        prototypeInstance = createBean(beanName, mbd, args);
                    }
                    finally {
                        afterPrototypeCreation(beanName);
                    }
                    bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
                }

                else {
                    String scopeName = mbd.getScope();
                    final Scope scope = this.scopes.get(scopeName);
                    if (scope == null) {
                        throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
                    }
                    try {
                        Object scopedInstance = scope.get(beanName, () -> {
                            beforePrototypeCreation(beanName);
                            try {
                                return createBean(beanName, mbd, args);
                            }
                            finally {
                                afterPrototypeCreation(beanName);
                            }
                        });
                        bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                    }
                    catch (IllegalStateException ex) {
                        throw new BeanCreationException(beanName,
                                "Scope '" + scopeName + "' is not active for the current thread; consider " +
                                "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
                                ex);
                    }
                }
            }
            catch (BeansException ex) {
                cleanupAfterBeanCreationFailure(beanName);
                throw ex;
            }
        }

        // Check if required type matches the type of the actual bean instance.
        if (requiredType != null && !requiredType.isInstance(bean)) {
            try {
                T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
                if (convertedBean == null) {
                    throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
                }
                return convertedBean;
            }
            catch (TypeMismatchException ex) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Failed to convert bean '" + name + "' to required type '" +
                            ClassUtils.getQualifiedName(requiredType) + "'", ex);
                }
                throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
            }
        }
        return (T) bean;
    }

注意3.4.6的代碼,會(huì)創(chuàng)建一個(gè)bean對(duì)象

   /**
     * Central method of this class: creates a bean instance,
     * populates the bean instance, applies post-processors, etc.
     * @see #doCreateBean
     */
    //核心方法,創(chuàng)建bean實(shí)例,填充bean實(shí)例,執(zhí)行各種后置處理器
    @Override
    protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
            throws BeanCreationException {

        if (logger.isTraceEnabled()) {
            logger.trace("Creating instance of bean '" + beanName + "'");
        }
        RootBeanDefinition mbdToUse = mbd;

        // Make sure bean class is actually resolved at this point, and
        // clone the bean definition in case of a dynamically resolved Class
        // which cannot be stored in the shared merged bean definition.
        //3.4.6.2.1
        Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
        if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
            mbdToUse = new RootBeanDefinition(mbd);
            mbdToUse.setBeanClass(resolvedClass);
        }

        // Prepare method overrides. 
        //3.4.6.2.2更新overloaded標(biāo)識(shí)值
        try {
            mbdToUse.prepareMethodOverrides();
        }
        catch (BeanDefinitionValidationException ex) {
            throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
                    beanName, "Validation of method overrides failed", ex);
        }

        try {
            // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
            // 3.4.6.2.3執(zhí)行InstantiationAwareBeanPostProcessor的postProcessBeforeInstantiation
            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 {
            //3.4.6.2.4實(shí)際上創(chuàng)建bean的方法
            Object beanInstance = doCreateBean(beanName, mbdToUse, args);
            if (logger.isTraceEnabled()) {
                logger.trace("Finished creating instance of bean '" + beanName + "'");
            }
            return beanInstance;
        }
        catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
            // A previously detected exception with proper bean creation context already,
            // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
            throw ex;
        }
        catch (Throwable ex) {
            throw new BeanCreationException(
                    mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
        }
    }

接著我們來看下AbstractAutowireCapableBeanFactory的doCreateBean方法。

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

        // Instantiate the bean.
        BeanWrapper instanceWrapper = null;
        if (mbd.isSingleton()) {
            instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
        }
        //3.4.6.2.4.1 
        if (instanceWrapper == null) {
            // 通過工廠方法或構(gòu)造器注入或通過無參構(gòu)造方法方法創(chuàng)建bean實(shí)例
            //若 bean 的配置信息中配置了 lookup-method 和 replace-method,則會(huì)使用CGLIB增強(qiáng)bean實(shí)例
            instanceWrapper = createBeanInstance(beanName, mbd, args);
        } 
        final Object bean = instanceWrapper.getWrappedInstance();
        Class<?> beanType = instanceWrapper.getWrappedClass();
        if (beanType != NullBean.class) {
            mbd.resolvedTargetType = beanType;
        }

        // Allow post-processors to modify the merged bean definition.
        synchronized (mbd.postProcessingLock) {
            if (!mbd.postProcessed) {
                try {
                    //3.4.6.2.4.2 執(zhí)行MergedBeanDefinitionPostProcessor,
                    //例如對(duì)merged beanDefinition做些緩存工作,也可以做屬性修改,
                    //例如對(duì)@ProConstruct和@PreDestroy注解的讀取處理在此處
                    applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
                }
                catch (Throwable ex) {
                    throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                            "Post-processing of merged bean definition failed", ex);
                }
                mbd.postProcessed = true;
            }
        }

        // 饑渴緩存單例bean,以便即使在諸如BeanFactoryAware之類的生命周期接口觸發(fā)時(shí)也能夠解析循環(huán)引用。
        boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
                isSingletonCurrentlyInCreation(beanName));
        if (earlySingletonExposure) {
            if (logger.isTraceEnabled()) {
                logger.trace("Eagerly caching bean '" + beanName +
                        "' to allow for resolving potential circular references");
            }
            //3.4.6.2.4.3
            addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
        }

        // Initialize the bean instance.
        Object exposedObject = bean;
        try {
            //3.4.6.2.4.4設(shè)置屬性
            //1)執(zhí)行InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation方法
            //2)如果beanDefinition設(shè)置了AUTOWIRE_BY_NAME或AUTOWIRE_BY_TYPE,通過名稱或類型填充autowired屬性
            //3)執(zhí)行InstantiationAwareBeanPostProcessor的postProcessProperties和postProcessPropertyValues填充屬性。
            //     執(zhí)行RequiredAnnotationBeanPostProcessor(@Required注解處理)、AutowiredAnnotationBeanPostProcessor(通過名稱或類型填充@Autowired和@Value和@javax.inject.Inject標(biāo)注的屬性)、CommonAnnotationBeanPostProcessor(jsr250注解如javax.annotation.Resource的處理)
            populateBean(beanName, mbd, instanceWrapper);
            //3.4.6.2.4.5執(zhí)行后置處理器
            //1)invokeAwareMethods,判斷bean是否為BeanNameAware、BeanClassLoaderAware、BeanFactoryAware并執(zhí)行相關(guān)實(shí)現(xiàn)方法
            //2)執(zhí)行BeanPostProcessor的postProcessBeforeInitialization方法
            //3)調(diào)用初始化方法 1.是InitializingBean則調(diào)用afterPropertiesSet()方法 2.檢查并調(diào)用beanDefinition的用戶自定義的initMethodName(就是@Bean配置的initMethod或xml配置的init-method)
            //4)執(zhí)行BeanPostProcessor的postProcessAfterInitialization方法
            exposedObject = initializeBean(beanName, exposedObject, mbd);
        }
        catch (Throwable ex) {
            if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
                throw (BeanCreationException) ex;
            }
            else {
                throw new BeanCreationException(
                        mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
            }
        }
        //3.4.6.2.4.6
        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()) {
                        throw new BeanCurrentlyInCreationException(beanName,
                                "Bean with name '" + beanName + "' has been injected into other beans [" +
                                StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
                                "] in its raw version as part of a circular reference, but has eventually been " +
                                "wrapped. This means that said other beans do not use the final version of the " +
                                "bean. This is often the result of over-eager type matching - consider using " +
                                "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
                    }
                }
            }
        }

        // Register bean as disposable.
        //3.4.6.2.4.7
        //調(diào)用registerDisposableBean方法,將單例實(shí)例bean包裹到DisposableBeanAdapter并放到disposable bean集合中,供容器close時(shí)執(zhí)行銷毀操作
        //自定義scope會(huì)將實(shí)例bean包裹到DisposableBeanAdapter,作為參數(shù)調(diào)用scope.registerDestructionCallback方法
        try {
            registerDisposableBeanIfNecessary(beanName, bean, mbd);
        }
        catch (BeanDefinitionValidationException ex) {
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
        }

        return exposedObject;
    }

分析DisposableBeanAdapter的destroy方法。

public void destroy() {
        if (!CollectionUtils.isEmpty(this.beanPostProcessors)) {
            //調(diào)用DestructionAwareBeanPostProcessor的postProcessBeforeDestruction
            //@PreDestroy聲明的方法在此時(shí)執(zhí)行
            for (DestructionAwareBeanPostProcessor processor : this.beanPostProcessors) {
                processor.postProcessBeforeDestruction(this.bean, this.beanName);
            }
        }

        //如果是DisposableBean調(diào)用bean的destroy方法
        if (this.invokeDisposableBean) {
            if (logger.isTraceEnabled()) {
                logger.trace("Invoking destroy() on bean with name '" + this.beanName + "'");
            }
            try {
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
                        ((DisposableBean) this.bean).destroy();
                        return null;
                    }, this.acc);
                }
                else {
                    ((DisposableBean) this.bean).destroy();
                }
            }
            catch (Throwable ex) {
                String msg = "Invocation of destroy method failed on bean with name '" + this.beanName + "'";
                if (logger.isDebugEnabled()) {
                    logger.info(msg, ex);
                }
                else {
                    logger.info(msg + ": " + ex);
                }
            }
        }
        //調(diào)用自定義的destroy方法(就是@Bean的destroy-method或XML配置的destroy-method)
        if (this.destroyMethod != null) {
            invokeCustomDestroyMethod(this.destroyMethod);
        }
        else if (this.destroyMethodName != null) {
            Method methodToCall = determineDestroyMethod(this.destroyMethodName);
            if (methodToCall != null) {
                invokeCustomDestroyMethod(methodToCall);
            }
        }
    }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容