【轉(zhuǎn)載】Spring Bean的生命周期(非常詳細(xì))

原文:
Spring Bean的生命周期(非常詳細(xì)) - Chandler Qian - 博客園 (cnblogs.com)
Spring作為當(dāng)前Java最流行、最強(qiáng)大的輕量級(jí)框架,受到了程序員的熱烈歡迎。準(zhǔn)確的了解Spring Bean的生命周期是非常必要的。我們通常使用ApplicationContext作為Spring容器。這里,我們講的也是 ApplicationContext中Bean的生命周期。而實(shí)際上BeanFactory也是差不多的,只不過處理器需要手動(dòng)注冊(cè)。

一、生命周期流程圖:

Spring Bean的完整生命周期從創(chuàng)建Spring容器開始,直到最終Spring容器銷毀Bean,這其中包含了一系列關(guān)鍵點(diǎn)。

image
image

若容器注冊(cè)了以上各種接口,程序那么將會(huì)按照以上的流程進(jìn)行。下面將仔細(xì)講解各接口作用。

二、各種接口方法分類

Bean的完整生命周期經(jīng)歷了各種方法調(diào)用,這些方法可以劃分為以下幾類:

1、Bean自身的方法 ?。骸 ∵@個(gè)包括了Bean本身調(diào)用的方法和通過配置文件中<bean>的init-method和destroy-method指定的方法

2、Bean級(jí)生命周期接口方法  :  這個(gè)包括了BeanNameAware、BeanFactoryAware、InitializingBean和DiposableBean這些接口的方法

3、容器級(jí)生命周期接口方法  :  這個(gè)包括了InstantiationAwareBeanPostProcessor 和 BeanPostProcessor 這兩個(gè)接口實(shí)現(xiàn),一般稱它們的實(shí)現(xiàn)類為“后處理器”。

4、工廠后處理器接口方法 ?。骸 ∵@個(gè)包括了AspectJWeavingEnabler, ConfigurationClassPostProcessor, CustomAutowireConfigurer等等非常有用的工廠后處理器  接口的方法。工廠后處理器也是容器級(jí)的。在應(yīng)用上下文裝配配置文件之后立即調(diào)用。

三、演示

我們用一個(gè)簡(jiǎn)單的Spring Bean來演示一下Spring Bean的生命周期。

1、首先是一個(gè)簡(jiǎn)單的Spring Bean,調(diào)用Bean自身的方法和Bean級(jí)生命周期接口方法,為了方便演示,它實(shí)現(xiàn)了BeanNameAware、BeanFactoryAware、InitializingBean和DiposableBean這4個(gè)接口,同時(shí)有2個(gè)方法,對(duì)應(yīng)配置文件中<bean>的init-method和destroy-method。如下:

package springBeanTest;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

/**
 * @author qsk
 */
public class Person implements BeanFactoryAware, BeanNameAware,
        InitializingBean, DisposableBean {

    private String name;
    private String address;
    private int phone;

    private BeanFactory beanFactory;
    private String beanName;

    public Person() {
        System.out.println("【構(gòu)造器】調(diào)用Person的構(gòu)造器實(shí)例化");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        System.out.println("【注入屬性】注入屬性name");
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        System.out.println("【注入屬性】注入屬性address");
        this.address = address;
    }

    public int getPhone() {
        return phone;
    }

    public void setPhone(int phone) {
        System.out.println("【注入屬性】注入屬性phone");
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "Person [address=" + address + ", name=" + name + ", phone="
                + phone + "]";
    }

    // 這是BeanFactoryAware接口方法
    @Override
    public void setBeanFactory(BeanFactory arg0) throws BeansException {
        System.out
                .println("【BeanFactoryAware接口】調(diào)用BeanFactoryAware.setBeanFactory()");
        this.beanFactory = arg0;
    }

    // 這是BeanNameAware接口方法
    @Override
    public void setBeanName(String arg0) {
        System.out.println("【BeanNameAware接口】調(diào)用BeanNameAware.setBeanName()");
        this.beanName = arg0;
    }

    // 這是InitializingBean接口方法
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out
                .println("【InitializingBean接口】調(diào)用InitializingBean.afterPropertiesSet()");
    }

    // 這是DiposibleBean接口方法
    @Override
    public void destroy() throws Exception {
        System.out.println("【DiposibleBean接口】調(diào)用DiposibleBean.destory()");
    }

    // 通過<bean>的init-method屬性指定的初始化方法
    public void myInit() {
        System.out.println("【init-method】調(diào)用<bean>的init-method屬性指定的初始化方法");
    }

    // 通過<bean>的destroy-method屬性指定的初始化方法
    public void myDestory() {
        System.out.println("【destroy-method】調(diào)用<bean>的destroy-method屬性指定的初始化方法");
    }
}

2、接下來是演示BeanPostProcessor接口的方法,如下:

package springBeanTest;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyBeanPostProcessor implements BeanPostProcessor {

    public MyBeanPostProcessor() {
        super();
        System.out.println("這是BeanPostProcessor實(shí)現(xiàn)類構(gòu)造器?。?);
        // TODO Auto-generated constructor stub
    }

    @Override
    public Object postProcessAfterInitialization(Object arg0, String arg1)
            throws BeansException {
        System.out
        .println("BeanPostProcessor接口方法postProcessAfterInitialization對(duì)屬性進(jìn)行更改!");
        return arg0;
    }

    @Override
    public Object postProcessBeforeInitialization(Object arg0, String arg1)
            throws BeansException {
        System.out
        .println("BeanPostProcessor接口方法postProcessBeforeInitialization對(duì)屬性進(jìn)行更改!");
        return arg0;
    }
}

如上,BeanPostProcessor接口包括2個(gè)方法postProcessAfterInitialization和postProcessBeforeInitialization,這兩個(gè)方法的第一個(gè)參數(shù)都是要處理的Bean對(duì)象,第二個(gè)參數(shù)都是Bean的name。返回值也都是要處理的Bean對(duì)象。這里要注意。

3、InstantiationAwareBeanPostProcessor 接口本質(zhì)是BeanPostProcessor的子接口,一般我們繼承Spring為其提供的適配器類InstantiationAwareBeanPostProcessor Adapter來使用它,如下:

package springBeanTest;

import java.beans.PropertyDescriptor;

import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;

public class MyInstantiationAwareBeanPostProcessor extends
        InstantiationAwareBeanPostProcessorAdapter {

    public MyInstantiationAwareBeanPostProcessor() {
        super();
        System.out
                .println("這是InstantiationAwareBeanPostProcessorAdapter實(shí)現(xiàn)類構(gòu)造器??!");
    }

    // 接口方法、實(shí)例化Bean之前調(diào)用
    @Override
    public Object postProcessBeforeInstantiation(Class beanClass,
            String beanName) throws BeansException {
        System.out
                .println("InstantiationAwareBeanPostProcessor調(diào)用postProcessBeforeInstantiation方法");
        return null;
    }

    // 接口方法、實(shí)例化Bean之后調(diào)用
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        System.out
                .println("InstantiationAwareBeanPostProcessor調(diào)用postProcessAfterInitialization方法");
        return bean;
    }

    // 接口方法、設(shè)置某個(gè)屬性時(shí)調(diào)用
    @Override
    public PropertyValues postProcessPropertyValues(PropertyValues pvs,
            PropertyDescriptor[] pds, Object bean, String beanName)
            throws BeansException {
        System.out
                .println("InstantiationAwareBeanPostProcessor調(diào)用postProcessPropertyValues方法");
        return pvs;
    }
}

這個(gè)有3個(gè)方法,其中第二個(gè)方法postProcessAfterInitialization就是重寫了BeanPostProcessor的方法。第三個(gè)方法postProcessPropertyValues用來操作屬性,返回值也應(yīng)該是PropertyValues對(duì)象。

4、演示工廠后處理器接口方法,如下:

package springBeanTest;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    public MyBeanFactoryPostProcessor() {
        super();
        System.out.println("這是BeanFactoryPostProcessor實(shí)現(xiàn)類構(gòu)造器??!");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0)
            throws BeansException {
        System.out
                .println("BeanFactoryPostProcessor調(diào)用postProcessBeanFactory方法");
        BeanDefinition bd = arg0.getBeanDefinition("person");
        bd.getPropertyValues().addPropertyValue("phone", "110");
    }

}

5、配置文件如下beans.xml,很簡(jiǎn)單,使用ApplicationContext,處理器不用手動(dòng)注冊(cè):

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
            http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

    <bean id="beanPostProcessor" class="springBeanTest.MyBeanPostProcessor">
    </bean>

    <bean id="instantiationAwareBeanPostProcessor" class="springBeanTest.MyInstantiationAwareBeanPostProcessor">
    </bean>

    <bean id="beanFactoryPostProcessor" class="springBeanTest.MyBeanFactoryPostProcessor">
    </bean>
    
    <bean id="person" class="springBeanTest.Person" init-method="myInit"
        destroy-method="myDestory" scope="singleton" p:name="張三" p:address="廣州"
        p:phone="15900000000" />

</beans>

6、下面測(cè)試一下:

package springBeanTest;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanLifeCycle {

    public static void main(String[] args) {

        System.out.println("現(xiàn)在開始初始化容器");

        ApplicationContext factory = new ClassPathXmlApplicationContext("springBeanTest/beans.xml");
        System.out.println("容器初始化成功");
        //得到Preson,并使用
        Person person = factory.getBean("person",Person.class);
        System.out.println(person);

        System.out.println("現(xiàn)在開始關(guān)閉容器!");
        ((ClassPathXmlApplicationContext)factory).registerShutdownHook();
    }
}

關(guān)閉容器使用的是實(shí)際是AbstractApplicationContext的鉤子方法。

我們來看一下結(jié)果:

現(xiàn)在開始初始化容器
2014-5-18 15:46:20 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@19a0c7c: startup date [Sun May 18 15:46:20 CST 2014]; root of context hierarchy
2014-5-18 15:46:20 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [springBeanTest/beans.xml]
這是BeanFactoryPostProcessor實(shí)現(xiàn)類構(gòu)造器!!
BeanFactoryPostProcessor調(diào)用postProcessBeanFactory方法
這是BeanPostProcessor實(shí)現(xiàn)類構(gòu)造器!!
這是InstantiationAwareBeanPostProcessorAdapter實(shí)現(xiàn)類構(gòu)造器?。?2014-5-18 15:46:20 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@9934d4: defining beans [beanPostProcessor,instantiationAwareBeanPostProcessor,beanFactoryPostProcessor,person]; root of factory hierarchy
InstantiationAwareBeanPostProcessor調(diào)用postProcessBeforeInstantiation方法
【構(gòu)造器】調(diào)用Person的構(gòu)造器實(shí)例化
InstantiationAwareBeanPostProcessor調(diào)用postProcessPropertyValues方法
【注入屬性】注入屬性address
【注入屬性】注入屬性name
【注入屬性】注入屬性phone
【BeanNameAware接口】調(diào)用BeanNameAware.setBeanName()
【BeanFactoryAware接口】調(diào)用BeanFactoryAware.setBeanFactory()
BeanPostProcessor接口方法postProcessBeforeInitialization對(duì)屬性進(jìn)行更改!
【InitializingBean接口】調(diào)用InitializingBean.afterPropertiesSet()
【init-method】調(diào)用<bean>的init-method屬性指定的初始化方法
BeanPostProcessor接口方法postProcessAfterInitialization對(duì)屬性進(jìn)行更改!
InstantiationAwareBeanPostProcessor調(diào)用postProcessAfterInitialization方法
容器初始化成功
Person [address=廣州, name=張三, phone=110]
現(xiàn)在開始關(guān)閉容器!
【DiposibleBean接口】調(diào)用DiposibleBean.destory()
【destroy-method】調(diào)用<bean>的destroy-method屬性指定的初始化方法
最后編輯于
?著作權(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),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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