Spring之bean的生命周期

Spring作为当前Java最流行、最强大的轻量级框架,受到了程序员的热烈欢迎。准确的了解Spring Bean的生命周期是非常必要的。我们通常使用ApplicationContext作为Spring容器。这里,我们讲的也是 ApplicationContext中Bean的生命周期。而实际上BeanFactory也是差不多的,只不过处理器需要手动注册。
一、生命周期流程图:
  Spring Bean的完整生命周期从创建Spring容器开始,直到最终Spring容器销毁Bean,这其中包含了一系列关键点。

Spring中Bean的生命周期

若容器注册了以上各种接口,程序那么将会按照以上的流程进行。下面将仔细讲解各接口作用。

二、各种接口方法分类
  Bean的完整生命周期经历了各种方法调用,这些方法可以划分为以下几类:
1.Bean自身的方法:这个包括了Bean本身调用的方法和通过配置文件中<bean>的init-methoddestroy-method指定的方法
2.Bean及生命周期接口方法:这个包括了BeanNameAwareBeanFactoryAwareInitializingBeanDiposableBean这些接口的方法
3.容器级生命周期接口方法:这个包括了InstantiationAwareBeanPostProcessorBeanPostProcessor 这两个接口实现,一般称它们的实现类为“后处理器”。
4.工厂后处理器接口方法:这个包括了AspectJWeavingEnabler, ConfigurationClassPostProcessor, CustomAutowireConfigurer等等非常有用的工厂后处理器接口的方法。工厂后处理器也是容器级的。在应用上下文装配配置文件之后立即调用。
  
三、演示
  我们用一个简单的Spring Bean来演示一下Spring Bean的生命周期。
1、首先是一个简单的Spring Bean,调用Bean自身的方法和Bean级生命周期接口方法,为了方便演示,它实现了BeanNameAware、BeanFactoryAware、InitializingBean和DiposableBean这4个接口,同时有2个方法,对应配置文件中<bean>的init-method和destroy-method。如下:

package com.kong.sitemush.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;

/**
 * Created by Kong on 2016/9/22.
 */
public class User implements BeanFactoryAware,BeanNameAware,InitializingBean,DisposableBean {

    private Long id;

    private String name;

    private String address;

    private BeanFactory beanFactory;

    private String beanName;

    public User(){
        System.out.println("创建了User 对象!");
    }
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        System.out.println("注入了User name!");
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    // 这是BeanFactoryAware接口方法
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()");
        this.beanFactory = beanFactory;
    }

    @Override
    public void setBeanName(String name) {
        System.out.println("调用【BeanNameAware】的setBeanName方法");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("调用【DisposableBean】的destroy方法!");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("调用【InitializingBean】的afterPropertiesSet方法");
    }
}

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

package com.kong.sitemush.bean;

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

/**
 * Created by Administrator on 2016/9/22.
 */
public class MyBeanPostProcessor implements BeanPostProcessor {



    public MyBeanPostProcessor(){
        super();
        System.out.println("调用MyBeanPostProcessor的构造方法!");
    }
    //初始化Bean之前调用
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("调用BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改!");
        return bean;
    }
    //初始化Bean之后调用
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("调用BeanPostProcessor接口的方法postProcessAfterInitialization对属性进行修改");
        return bean;
    }
}

如上,BeanPostProcessor接口包括2个方法postProcessAfterInitialization和postProcessBeforeInitialization,这两个方法的第一个参数都是要处理的Bean对象,第二个参数都是Bean的name。返回值也都是要处理的Bean对象。这里要注意。

3、InstantiationAwareBeanPostProcessor 接口本质是BeanPostProcessor的子接口,一般我们继承Spring为其提供的适配器类InstantiationAwareBeanPostProcessor Adapter来使用它,如下:

package com.kong.sitemush.bean;

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

import java.beans.PropertyDescriptor;

/**
 * Created by Administrator on 2016/9/22.
 *  public class MyInstantiationAwareBeanPostProcessor extends
 10         InstantiationAwareBeanPostProcessorAdapter {
 */
public class MyInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter{

    public MyInstantiationAwareBeanPostProcessor(){
        super();
        System.out.println("这是InstantiationAwareBeanPostProcessorAdapter的构造器!!");
    }

    // 接口方法、实例化Bean之前调用
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        System.out.println("InstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation方法");
        return super.postProcessBeforeInstantiation(beanClass,beanName);
    }



    //接口方法Bean实现之后调用
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("InstantiationAwarePostProcessor调用postProcessAfterInitialization方法");
        return super.postProcessAfterInitialization(bean, beanName);
    }


    // 接口方法、设置某个属性时调用
    @Override
    public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
        System.out.println("调用InstantiationAwarePostProcessor的postProcessPropertyValues方法");
        return super.postProcessPropertyValues(pvs, pds, bean, beanName);
    }
}

这个有3个方法,其中第二个方法postProcessAfterInitialization就是重写了BeanPostProcessor的方法。第三个方法postProcessPropertyValues用来操作属性,返回值也应该是PropertyValues对象。

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

package com.kong.sitemush.bean;

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

/**
 * Created by Administrator on 2016/9/22.
 */
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    public MyBeanFactoryPostProcessor(){
        super();
        System.out.println("MyBeanFactoryPostProcessor的构造方法");
    }

   /**
    这时候所有的Bean定义已经被加载,但是没有进行实例化
    修改应用程序上下文的内部bean工厂标准后初始化。所有bean定义将被加载,但没有实例化bean将。
    这允许覆盖或添加属性甚至eager-initializing
    */
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("调用BeanFactoryPostProcessor 的postProcessBeanFactory方法");
        BeanDefinition bd = beanFactory.getBeanDefinition("user");
        bd.getPropertyValues().addPropertyValue("address", "黑龙江哈尔滨松北区");
    }
}

5、配置文件如下beans.xml,很简单,使用ApplicationContext,处理器不用手动注册:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"
       default-lazy-init="true">

    <bean id="user" class="com.kong.sitemush.bean.User">
        <property name="name" value="郭之源"/>
    </bean>

    <bean id="myBeanFactoryPostProcessor" class="com.kong.sitemush.bean.MyBeanFactoryPostProcessor"/>

    <bean id="myInstantiationAwareBeanPostProcessor" class="com.kong.sitemush.bean.MyInstantiationAwareBeanPostProcessor"/>

    <bean id="myBeanPostProcessor" class="com.kong.sitemush.bean.MyBeanPostProcessor"/>
</beans>

6、下面测试一下:

package kong.java;


import com.kong.sitemush.bean.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created by Administrator on 2016/9/22.
 */
public class SpringBeanLifecycleTest {


    @Test
    public void testLifeCycle(){
        System.out.println("现在开始初始化容器");

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

        System.out.println("现在开始关闭容器!");
        ((ClassPathXmlApplicationContext)factory).registerShutdownHook();
    }
}

关闭容器使用的是实际是AbstractApplicationContext的钩子方法。

我们来看一下结果:

现在开始初始化容器
MyBeanFactoryPostProcessor的构造方法
调用BeanFactoryPostProcessor 的postProcessBeanFactory方法
这是InstantiationAwareBeanPostProcessorAdapter的构造器!!
调用MyBeanPostProcessor的构造方法!
容器初始化成功
InstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation方法
创建了User 对象!
调用InstantiationAwarePostProcessor的postProcessPropertyValues方法
注入了User name!
调用【BeanNameAware】的setBeanName方法
【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()
调用BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改!
调用【InitializingBean】的afterPropertiesSet方法
InstantiationAwarePostProcessor调用postProcessAfterInitialization方法
调用BeanPostProcessor接口的方法postProcessAfterInitialization对属性进行修改
com.kong.sitemush.bean.User@7f3399d7
现在开始关闭容器!
调用【DisposableBean】的destroy方法!

Process finished with exit code 0
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容