一線大廠面試必問spring源碼系列之「Bean的生命週期」

目錄

  • 1. Bean的實例化概述
  • 2. 流程概覽
  • 3. 源碼分析
  • 4. 演示
  • 4. 總結

爲源碼付出的每一分努力都不會白費。

1. Bean的實例化概述

前一篇分析了BeanDefinition的封裝過程,最終將beanName與BeanDefinition以一對一映射關係放到beanDefinitionMap容器中,這一篇重點分析如何利用bean的定義信息BeanDefinition實例化bean。

2. 流程概覽

其實bean的實例化過程比較複雜,中間細節很多,爲了抓住重點,先將核心流程梳理出來,主要包含以下幾個流程:

step1: 通過反射創建實例;
step2:給實例屬性賦初始值;
step3:如果Bean類實現BeanNameAware接口,則將通過傳遞Bean的名稱來調用setBeanName()方法;如果Bean類實現BeanClassLoaderAware接口,則將通過傳遞加載此Bean的ClassLoader對象的實例來調用setBeanClassLoader()方法;如果Bean類實現BeanFactoryAware接口,則將通過傳遞BeanFactory對象的實例來調用setBeanFactory()方法;
step4: 如果有類實現BeanPostProcessors接口,則將在初始化之前調用postProcessBeforeInitialization()方法;
step5:如果Bean類實現了InitializingBean接口,將調用afterPropertiesSet()方法,如果配置文件中的Bean定義包含init-method屬性,則該屬性的值將解析爲Bean類中的方法名稱,並將調用該方法;
step6: 如果有類實現BeanPostProcessors接口,則將在初始化之後調用postProcessAfterInitialization()方法;
step7:如果Bean類實現DisposableBean接口,則當Application不再需要Bean引用時,將調用destroy()方法;如果配置文件中的Bean定義包含destroy-method屬性,那麼將調用Bean類中的相應方法定義。

3. 源碼分析

進入AbstractApplicationContext中的fresh()方法,找到finishBeanFactoryInitialization(beanFactory)方法,該類是bean的實例化的入口,具體的實例化由preInstantiateSingletons()方法觸發,見如下代碼:

 <code-box id="xHFQpn" style="padding: 0px; margin: 10px 0px; color: rgb(34, 34, 34); font-family: -apple-system, &quot;SF UI Text&quot;, Arial, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei&quot;, &quot;WenQuanYi Micro Hei&quot;, sans-serif; font-size: 15.5px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgba(255, 255, 255, 0.9); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; position: relative; display: block;"><pre id="pre-xHFQpn" class="hljs armasm mCustomScrollbar _mCS_1 mCS-autoHide" style="padding: 10px !important; margin: 5px 15px; overflow: visible; display: block; background: rgb(43, 43, 43); color: rgb(248, 248, 242); touch-action: pinch-zoom; font-size: 14px !important; font-weight: 400; font-family: &quot;Ubuntu Mono&quot;, monospace !important; white-space: pre; overflow-wrap: normal; border-radius: 5px !important; word-break: break-all; counter-reset: itemcounter 0; line-height: 1.5 !important; position: relative;">

<code-pre class="code-pre" id="pre-dCT6nD" style="padding: 0px 0px 0px 10px; margin: 0px; position: relative; display: block; left: 30px; border-left: 1px solid rgb(153, 153, 153);">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.
        //xml解析時,把所有beanName都緩存到beanDefinitionNames了        List<String> beanNames = new ArrayList<>(this.beanDefinitionNames); 
        // Trigger initialization of all non-lazy singleton beans...        for (String beanName : beanNames) {
            //把父BeanDefinition裏面的屬性拿到子BeanDefinition中           RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);             //如果不是抽象的,單例的,非懶加載的就實例化
            if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
                //判斷bean是否實現了FactoryBean接口              if (isFactoryBean(beanName)) {
                    Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);                  if (bean instanceof FactoryBean) {
                        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 {
                    // 實例化過程
                    getBean(beanName);              }
            }
        }</code-pre> 

</pre></code-box> 

上述代碼主要看getBean方法,隨後進入doGetBean方法:

 <code-box id="iaxDFz" style="padding: 0px; margin: 10px 0px; color: rgb(34, 34, 34); font-family: -apple-system, &quot;SF UI Text&quot;, Arial, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei&quot;, &quot;WenQuanYi Micro Hei&quot;, sans-serif; font-size: 15.5px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgba(255, 255, 255, 0.9); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; position: relative; display: block;"><pre id="pre-iaxDFz" class="hljs pgsql mCustomScrollbar _mCS_2 mCS-autoHide" style="padding: 10px !important; margin: 5px 15px; overflow: visible; display: block; background: rgb(43, 43, 43); color: rgb(248, 248, 242); touch-action: pinch-zoom; font-size: 14px !important; font-weight: 400; font-family: &quot;Ubuntu Mono&quot;, monospace !important; white-space: pre; overflow-wrap: normal; border-radius: 5px !important; word-break: break-all; counter-reset: itemcounter 0; line-height: 1.5 !important; position: relative;">

 <code-pre class="code-pre" id="pre-QA78ZG" style="padding: 0px 0px 0px 10px; margin: 0px; position: relative; display: block; left: 30px; border-left: 1px solid rgb(153, 153, 153);">protected <T> T doGetBean(
            String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
            throws BeansException {

        String beanName = transformedBeanName(name);
        Object bean;

        // 從緩存中獲取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 {
            // Fail if we're already creating this bean instance:  // We're assumably within a circular reference.
            if (isPrototypeCurrentlyInCreation(beanName)) {
                throw new BeanCurrentlyInCreationException(beanName);
            }

            // Check if bean definition exists in this factory.
            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 {
                RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                checkMergedBeanDefinition(mbd, beanName, args);

                // Guarantee initialization of beans that the current bean 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
                                // 創建bean實例
                if (mbd.isSingleton()) {
                    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);
                }
...
}</code-pre> 

</pre></code-box> 

由上述代碼可知,先從緩存中獲取bean,如果沒有,則創建bean,最重要的方法就是getSingleton,該方法第二個參數是個函數式接口,進入getSingleton方法,當調用singletonObject = singletonFactory.getObject()時,會觸發函數式接口中的createBean方法,隨後一路進入doCreateBean,這個方法裏面完成了所有實例化所需的步驟:

 <code-box id="fmyDEp" style="padding: 0px; margin: 10px 0px; color: rgb(34, 34, 34); font-family: -apple-system, &quot;SF UI Text&quot;, Arial, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei&quot;, &quot;WenQuanYi Micro Hei&quot;, sans-serif; font-size: 15.5px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgba(255, 255, 255, 0.9); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; position: relative; display: block;"><pre id="pre-fmyDEp" class="hljs processing mCustomScrollbar _mCS_3 mCS-autoHide" style="padding: 10px !important; margin: 5px 15px; overflow: visible; display: block; background: rgb(43, 43, 43); color: rgb(248, 248, 242); touch-action: pinch-zoom; font-size: 14px !important; font-weight: 400; font-family: &quot;Ubuntu Mono&quot;, monospace !important; white-space: pre; overflow-wrap: normal; border-radius: 5px !important; word-break: break-all; counter-reset: itemcounter 0; line-height: 1.5 !important; position: relative;">

 <code-pre class="code-pre" id="pre-ZEZrYQ" style="padding: 0px 0px 0px 10px; margin: 0px; position: relative; display: block; left: 30px; border-left: 1px solid rgb(153, 153, 153);">protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
            throws BeanCreationException {

        // Instantiate the bean.
        // 真正開始創建bean的實例.
        BeanWrapper instanceWrapper = null;
        if (mbd.isSingleton()) {
            instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
        }
        if (instanceWrapper == null) {
            instanceWrapper = createBeanInstance(beanName, mbd, args);
        }
        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 {
                    applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
                }
                catch (Throwable ex) {
                    throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                            "Post-processing of merged bean definition failed", ex);
                }
                mbd.postProcessed = true;
            }
        }

        // Eagerly cache singletons to be able to resolve circular references
        // even when triggered by lifecycle interfaces like BeanFactoryAware.
        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");
            }
            addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
        }

        // Initialize the bean instance.
        Object exposedObject = bean;
        try {
            // 屬性賦值
            populateBean(beanName, mbd, instanceWrapper);
            // 初始化bean
            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);
            }
        }

        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 " +
                                "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
                    }
                }
            }
        }

        // Register bean as disposable.
                // 有必要時,註冊bean的銷燬
        try {
            registerDisposableBeanIfNecessary(beanName, bean, mbd);
        }
        catch (BeanDefinitionValidationException ex) {
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
        }

        return exposedObject;
    }</code-pre> 

</pre></code-box> 

從上述源碼中看出bean的實例化主要分爲以下三步:
step1:bean的創建;
step2:給bean的屬性賦值;
step3:bean的初始化;
接着得到exposedObject這個已經完全實例化後的bean返回,其中當有必要時,註冊bean的銷燬,後面再詳細看,先抓住主要流程。其中step3也是比較重要的方法,進入該方法:

 <code-box id="8HWMzh" style="padding: 0px; margin: 10px 0px; color: rgb(34, 34, 34); font-family: -apple-system, &quot;SF UI Text&quot;, Arial, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei&quot;, &quot;WenQuanYi Micro Hei&quot;, sans-serif; font-size: 15.5px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgba(255, 255, 255, 0.9); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; position: relative; display: block;"><pre id="pre-8HWMzh" class="hljs livescript mCustomScrollbar _mCS_4 mCS-autoHide" style="padding: 10px !important; margin: 5px 15px; overflow: visible; display: block; background: rgb(43, 43, 43); color: rgb(248, 248, 242); touch-action: pinch-zoom; font-size: 14px !important; font-weight: 400; font-family: &quot;Ubuntu Mono&quot;, monospace !important; white-space: pre; overflow-wrap: normal; border-radius: 5px !important; word-break: break-all; counter-reset: itemcounter 0; line-height: 1.5 !important; position: relative;">

 <code-pre class="code-pre" id="pre-8EN74w" style="padding: 0px 0px 0px 10px; margin: 0px; position: relative; display: block; left: 30px; border-left: 1px solid rgb(153, 153, 153);">protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {  invokeAwareMethods(beanName, bean);  return null;  }, getAccessControlContext());  }  else {  // 激活aware接口  invokeAwareMethods(beanName, bean);  }    Object wrappedBean = bean;  if (mbd == null || !mbd.isSynthetic()) {  // 初始化前處理的beanPostProcessor  wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);  }    try {  // 激活 init-method方法  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()) {  // 初始化後處理的beanPostProcessor  wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);  }    return wrappedBean;  }</code-pre> 

</pre></code-box> 

從上面源碼可知,梳理出主要的四個步驟:
step1:激活aware接口,完成aware接口的相關操作;
step2:初始化前處理的beanPostProcessor;
step3:完成init-method方法;
step4:初始化後處理的beanPostProcessor;
BeanPostProcessor作用是對初始化後的bean進行增強處理,在該階段 BeanPostProcessor 會處理當前容器內所有符合條件的實例化後的 bean 對象。它主要是對 Spring 容器提供的 bean 實例對象進行有效的擴展,允許Spring在初始化 bean 階段對其進行定製化修改,如處理標記接口或者爲其提供代理實現。

4. 演示

定義一個MyBeanPostProcessor實現BeanPostProcessor接口

 <code-box id="TNQzyj" style="padding: 0px; margin: 10px 0px; color: rgb(34, 34, 34); font-family: -apple-system, &quot;SF UI Text&quot;, Arial, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei&quot;, &quot;WenQuanYi Micro Hei&quot;, sans-serif; font-size: 15.5px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgba(255, 255, 255, 0.9); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; position: relative; display: block;"><pre id="pre-TNQzyj" class="hljs java mCustomScrollbar _mCS_5 mCS-autoHide" style="padding: 10px !important; margin: 5px 15px; overflow: visible; display: block; background: rgb(43, 43, 43); color: rgb(248, 248, 242); touch-action: pinch-zoom; font-size: 14px !important; font-weight: 400; font-family: &quot;Ubuntu Mono&quot;, monospace !important; white-space: pre; overflow-wrap: normal; border-radius: 5px !important; word-break: break-all; counter-reset: itemcounter 0; line-height: 1.5 !important; position: relative;">

<code-pre class="code-pre" id="pre-CyN7jd" style="padding: 0px 0px 0px 10px; margin: 0px; position: relative; display: block; left: 30px; border-left: 1px solid rgb(153, 153, 153);">public class MyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("post Process Before Initialization 被調用...");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("post Process after Initialization 被調用...");
        return bean;
    }
}</code-pre> 

</pre></code-box> 

定義一個LifeCycleBean類,實現如下接口:

 <code-box id="WiaQRB" style="padding: 0px; margin: 10px 0px; color: rgb(34, 34, 34); font-family: -apple-system, &quot;SF UI Text&quot;, Arial, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei&quot;, &quot;WenQuanYi Micro Hei&quot;, sans-serif; font-size: 15.5px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgba(255, 255, 255, 0.9); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; position: relative; display: block;"><pre id="pre-WiaQRB" class="hljs cs mCustomScrollbar _mCS_6 mCS-autoHide" style="padding: 10px !important; margin: 5px 15px; overflow: visible; display: block; background: rgb(43, 43, 43); color: rgb(248, 248, 242); touch-action: pinch-zoom; font-size: 14px !important; font-weight: 400; font-family: &quot;Ubuntu Mono&quot;, monospace !important; white-space: pre; overflow-wrap: normal; border-radius: 5px !important; word-break: break-all; counter-reset: itemcounter 0; line-height: 1.5 !important; position: relative;">

<code-pre class="code-pre" id="pre-ZG6ZfE" style="padding: 0px 0px 0px 10px; margin: 0px; position: relative; display: block; left: 30px; border-left: 1px solid rgb(153, 153, 153);">public class LifeCycleBean implements BeanNameAware, BeanFactoryAware, BeanClassLoaderAware,
        InitializingBean, DisposableBean {

    private String property;

    public String getProperty() {
        return property;
    }

    public void setProperty(String property) {
        System.out.println("屬性注入....");
        this.property = property;
    }

    public LifeCycleBean(){
        System.out.println("構造函數調用...");
    }
    @Override  public void setBeanClassLoader(ClassLoader classLoader) {
        System.out.println("BeanClassLoaderAware 被調用...");
    }

    @Override  public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("BeanFactoryAware 被調用...");
    }

    @Override  public void setBeanName(String name) {
        System.out.println("BeanNameAware 被調用...");
    }

    @Override  public void destroy() throws Exception {
        System.out.println("DisposableBean destroy 被調用...");
    }

    @Override  public void afterPropertiesSet() throws Exception {
        System.out.println("InitializingBean afterPropertiesSet 被調用...");
    }

    public void initMethod(){
        System.out.println("init-method 被調用...");
    }

    public void destroyMethod(){
        System.out.println("destroy-method 被調用...");
    }

    public void display(){
        System.out.println("方法調用...");
    }

}</code-pre> 

</pre></code-box> 

指定配置文件spring.xml,配置init-methoddestroy-method方法

 <code-box id="n3hbaF" style="padding: 0px; margin: 10px 0px; color: rgb(34, 34, 34); font-family: -apple-system, &quot;SF UI Text&quot;, Arial, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei&quot;, &quot;WenQuanYi Micro Hei&quot;, sans-serif; font-size: 15.5px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgba(255, 255, 255, 0.9); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; position: relative; display: block;"><pre id="pre-n3hbaF" class="hljs javascript mCustomScrollbar _mCS_7 mCS-autoHide" style="padding: 10px !important; margin: 5px 15px; overflow: visible; display: block; background: rgb(43, 43, 43); color: rgb(248, 248, 242); touch-action: pinch-zoom; font-size: 14px !important; font-weight: 400; font-family: &quot;Ubuntu Mono&quot;, monospace !important; white-space: pre; overflow-wrap: normal; border-radius: 5px !important; word-break: break-all; counter-reset: itemcounter 0; line-height: 1.5 !important; position: relative;">

 <code-pre class="code-pre" id="pre-xNSXpG" style="padding: 0px 0px 0px 10px; margin: 0px; position: relative; display: block; left: 30px; border-left: 1px solid rgb(153, 153, 153);"><bean id="lifeCycle" class="com.wzj.bean.LifeCycleBean"
          init-method="initMethod" destroy-method="destroyMethod">
        <property name="property" value="property"/>  </bean>
    <bean id="myBeanPostProcessor" class="com.wzj.bean.MyBeanPostProcessor" >
    </bean></code-pre> 

</pre></code-box> 

測試類如下:

 <code-box id="dzMaNy" style="padding: 0px; margin: 10px 0px; color: rgb(34, 34, 34); font-family: -apple-system, &quot;SF UI Text&quot;, Arial, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei&quot;, &quot;WenQuanYi Micro Hei&quot;, sans-serif; font-size: 15.5px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgba(255, 255, 255, 0.9); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; position: relative; display: block;"><pre id="pre-dzMaNy" class="hljs groovy mCustomScrollbar _mCS_8 mCS-autoHide" style="padding: 10px !important; margin: 5px 15px; overflow: visible; display: block; background: rgb(43, 43, 43); color: rgb(248, 248, 242); touch-action: pinch-zoom; font-size: 14px !important; font-weight: 400; font-family: &quot;Ubuntu Mono&quot;, monospace !important; white-space: pre; overflow-wrap: normal; border-radius: 5px !important; word-break: break-all; counter-reset: itemcounter 0; line-height: 1.5 !important; position: relative;">

<code-pre class="code-pre" id="pre-4hnwjM" style="padding: 0px 0px 0px 10px; margin: 0px; position: relative; display: block; left: 30px; border-left: 1px solid rgb(153, 153, 153);">@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring.xml"})
public class TestSpring {

    @Test
    public void testLifeCycleBean() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

    }</code-pre> 

</pre></code-box> 

執行結果:

 <code-box id="mndr4h" style="padding: 0px; margin: 10px 0px; color: rgb(34, 34, 34); font-family: -apple-system, &quot;SF UI Text&quot;, Arial, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei&quot;, &quot;WenQuanYi Micro Hei&quot;, sans-serif; font-size: 15.5px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgba(255, 255, 255, 0.9); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; position: relative; display: block;"><pre id="pre-mndr4h" class="hljs erlang mCustomScrollbar _mCS_9 mCS-autoHide" style="padding: 10px !important; margin: 5px 15px; overflow: visible; display: block; background: rgb(43, 43, 43); color: rgb(248, 248, 242); touch-action: pinch-zoom; font-size: 14px !important; font-weight: 400; font-family: &quot;Ubuntu Mono&quot;, monospace !important; white-space: pre; overflow-wrap: normal; border-radius: 5px !important; word-break: break-all; counter-reset: itemcounter 0; line-height: 1.5 !important; position: relative;">

<code-pre class="code-pre" id="pre-e4R3km" style="padding: 0px 0px 0px 10px; margin: 0px; position: relative; display: block; left: 30px; border-left: 1px solid rgb(153, 153, 153);">構造函數調用...
屬性注入....
BeanNameAware 被調用...
BeanClassLoaderAware 被調用...
BeanFactoryAware 被調用...
post Process Before Initialization 被調用...
InitializingBean afterPropertiesSet 被調用...
init-method 被調用...
post Process after Initialization 被調用...
DisposableBean destroy 被調用...
destroy-method 被調用...</code-pre> 

</pre></code-box> 

4. 總結

本篇從一個初學者的角度概覽了bean的整個生命週期,並描述了其中的主要流程,閱讀源碼的初始階段,優先抓住主要流程,別陷入細節,並通過跑案例、寫註解、畫流程圖等方式加深理解,後續將繼續分析bean實例化中的核心流程、設計思想等。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章