Spring源码学习--Bean的生命周期

Spring作为当前Java最流行、最强大的轻量级框架,受到了程序员的热烈欢迎。准确的了解Spring Bean的生命周期是非常必要的。我们通常使用ApplicationContext作为Spring容器。这里,我们讲的也是 ApplicationContext中Bean的生命周期。而实际上BeanFactory也是差不多的,只不过处理器需要手动注册。

一、生命周期流程图:

  Spring Bean的完整生命周期从创建Spring容器开始,直到最终Spring容器销毁Bean,这其中包含了一系列关键点。

 

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

 

二、各种接口方法分类

Bean的完整生命周期经历了各种方法调用,这些方法可以划分为以下几类:

1、Bean自身的方法  :  这个包括了Bean本身调用的方法和通过配置文件中<bean>的init-method和destroy-method指定的方法

2、Bean级生命周期接口方法  :  这个包括了BeanNameAware、BeanFactoryAware、InitializingBean和DiposableBean这些接口的方法

3、容器级生命周期接口方法  :  这个包括了InstantiationAwareBeanPostProcessor 和 BeanPostProcessor 这两个接口实现,一般称它们的实现类为“后处理器”。

4、工厂后处理器接口方法  :  这个包括了AspectJWeavingEnabler, ConfigurationClassPostProcessor, CustomAutowireConfigurer等等非常有用的工厂后处理器  接口的方法。工厂后处理器也是容器级的。在应用上下文装配配置文件之后立即调用。

  

三、演示

我们用一个简单的Spring Bean来演示一下Spring Bean的生命周期。

1、首先是一个简单的Spring Bean,调用Bean自身的方法和Bean级生命周期接口方法,为了方便演示,它实现了BeanNameAware、BeanFactoryAware、InitializingBean和DiposableBean这4个接口,同时有2个方法,对应配置文件中<bean>的init-method和destroy-method。如下:

[java]  view plain  copy
 print ?
  1.  public class Person implements BeanFactoryAware, BeanNameAware,  
  2.          InitializingBean, DisposableBean {  
  3.    
  4.      private String name;  
  5.      private String address;  
  6.      private int phone;  
  7.    
  8.      private BeanFactory beanFactory;  
  9.      private String beanName;  
  10.    
  11.      public Person() {  
  12.          System.out.println("【构造器】调用Person的构造器实例化");  
  13.      }  
  14.    
  15.      public String getName() {  
  16.          return name;  
  17.      }  
  18.    
  19.      public void setName(String name) {  
  20.          System.out.println("【注入属性】注入属性name");  
  21.          this.name = name;  
  22.      }  
  23.    
  24.      public String getAddress() {  
  25.          return address;  
  26.      }  
  27.    
  28.      public void setAddress(String address) {  
  29.          System.out.println("【注入属性】注入属性address");  
  30.          this.address = address;  
  31.      }  
  32.    
  33.      public int getPhone() {  
  34.          return phone;  
  35.      }  
  36.    
  37.      public void setPhone(int phone) {  
  38.          System.out.println("【注入属性】注入属性phone");  
  39.          this.phone = phone;  
  40.      }  
  41.    
  42.      @Override  
  43.      public String toString() {  
  44.          return "Person [address=" + address + ", name=" + name + ", phone="  
  45.                  + phone + "]";  
  46.      }  
  47.    
  48.      // 这是BeanFactoryAware接口方法  
  49.      @Override  
  50.      public void setBeanFactory(BeanFactory arg0) throws BeansException {  
  51.          System.out  
  52.                 .println("【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()");  
  53.          this.beanFactory = arg0;  
  54.      }  
  55.    
  56.      // 这是BeanNameAware接口方法  
  57.      @Override  
  58.      public void setBeanName(String arg0) {  
  59.          System.out.println("【BeanNameAware接口】调用BeanNameAware.setBeanName()");  
  60.          this.beanName = arg0;  
  61.      }  
  62.    
  63.      // 这是InitializingBean接口方法  
  64.      @Override  
  65.      public void afterPropertiesSet() throws Exception {  
  66.          System.out  
  67.                  .println("【InitializingBean接口】调用InitializingBean.afterPropertiesSet()");  
  68.      }  
  69.    
  70.      // 这是DiposibleBean接口方法  
  71.      @Override  
  72.      public void destroy() throws Exception {  
  73.          System.out.println("【DiposibleBean接口】调用DiposibleBean.destory()");  
  74.      }  
  75.    
  76.      // 通过<bean>的init-method属性指定的初始化方法  
  77.      public void myInit() {  
  78.          System.out.println("【init-method】调用<bean>的init-method属性指定的初始化方法");  
  79.      }  
  80.    
  81.      // 通过<bean>的destroy-method属性指定的初始化方法  
  82.      public void myDestory() {  
  83.          System.out.println("【destroy-method】调用<bean>的destroy-method属性指定的初始化方法");  
  84.      }  
  85. }  

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

[java]  view plain  copy
 print ?
  1. public class MyBeanPostProcessor implements BeanPostProcessor {  
  2.    
  3.      public MyBeanPostProcessor() {  
  4.          super();  
  5.          System.out.println("这是BeanPostProcessor实现类构造器!!");  
  6.          // TODO Auto-generated constructor stub  
  7.      }  
  8.    
  9.      @Override  
  10.      public Object postProcessAfterInitialization(Object arg0, String arg1)  
  11.              throws BeansException {  
  12.          System.out  
  13.          .println("BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改!");  
  14.          return arg0;  
  15.      }  
  16.    
  17.      @Override  
  18.      public Object postProcessBeforeInitialization(Object arg0, String arg1)  
  19.              throws BeansException {  
  20.          System.out  
  21.          .println("BeanPostProcessor接口方法postProcessBeforeInitialization对属性进行更改!");  
  22.          return arg0;  
  23.      }  
  24. }  

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

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

[java]  view plain  copy
 print ?
  1.  public class MyInstantiationAwareBeanPostProcessor extends  
  2.          InstantiationAwareBeanPostProcessorAdapter {  
  3.    
  4.      public MyInstantiationAwareBeanPostProcessor() {  
  5.          super();  
  6.          System.out  
  7.                  .println("这是InstantiationAwareBeanPostProcessorAdapter实现类构造器!!");  
  8.      }  
  9.    
  10.      // 接口方法、实例化Bean之前调用  
  11.      @Override  
  12.      public Object postProcessBeforeInstantiation(Class beanClass,  
  13.              String beanName) throws BeansException {  
  14.          System.out  
  15.                  .println("InstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation方法");  
  16.          return null;  
  17.      }  
  18.    
  19.      // 接口方法、实例化Bean之后调用  
  20.      @Override  
  21.      public Object postProcessAfterInitialization(Object bean, String beanName)  
  22.              throws BeansException {  
  23.          System.out  
  24.                  .println("InstantiationAwareBeanPostProcessor调用postProcessAfterInitialization方法");  
  25.          return bean;  
  26.      }  
  27.    
  28.      // 接口方法、设置某个属性时调用  
  29.      @Override  
  30.      public PropertyValues postProcessPropertyValues(PropertyValues pvs,  
  31.              PropertyDescriptor[] pds, Object bean, String beanName)  
  32.              throws BeansException {  
  33.          System.out  
  34.                  .println("InstantiationAwareBeanPostProcessor调用postProcessPropertyValues方法");  
  35.          return pvs;  
  36.      }  
  37. }  
这个有3个方法,其中第二个方法 postProcessAfterInitialization就是重写了BeanPostProcessor的方法。第三个方法postProcessPropertyValues用来操作属性,返回值也应该是PropertyValues对象。
4、演示工厂后处理器接口方法,如下:
[java]  view plain  copy
 print ?
  1. public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {  
  2.    
  3.      public MyBeanFactoryPostProcessor() {  
  4.          super();  
  5.          System.out.println("这是BeanFactoryPostProcessor实现类构造器!!");  
  6.      }  
  7.    
  8.      @Override  
  9.      public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0)  
  10.              throws BeansException {  
  11.          System.out  
  12.                  .println("BeanFactoryPostProcessor调用postProcessBeanFactory方法");  
  13.          BeanDefinition bd = arg0.getBeanDefinition("person");  
  14.          bd.getPropertyValues().addPropertyValue("phone""110");  
  15.      }  
  16.    
  17.  }  
5、配置文件如下beans.xml,很简单,使用ApplicationContext,处理器不用手动注册:
[html]  view plain  copy
 print ?
  1. <bean id="beanPostProcessor" class="springBeanTest.MyBeanPostProcessor">  
  2.    </bean>  
  3.   
  4.    <bean id="instantiationAwareBeanPostProcessor" class="springBeanTest.MyInstantiationAwareBeanPostProcessor">  
  5.    </bean>  
  6.   
  7.    <bean id="beanFactoryPostProcessor" class="springBeanTest.MyBeanFactoryPostProcessor">  
  8.    </bean>  
  9.      
  10.    <bean id="person" class="springBeanTest.Person" init-method="myInit"  
  11.        destroy-method="myDestory" scope="singleton" p:name="张三" p:address="广州"  
  12.        p:phone="15900000000" />  
6、下面测试一下:
[java]  view plain  copy
 print ?
  1. public class BeanLifeCycle {  
  2.    
  3.      public static void main(String[] args) {  
  4.    
  5.          System.out.println("现在开始初始化容器");  
  6.            
  7.          ApplicationContext factory = new ClassPathXmlApplicationContext("springBeanTest/beans.xml");  
  8.          System.out.println("容器初始化成功");      
  9.          //得到Preson,并使用  
  10.          Person person = factory.getBean("person",Person.class);  
  11.          System.out.println(person);  
  12.            
  13.          System.out.println("现在开始关闭容器!");  
  14.          ((ClassPathXmlApplicationContext)factory).registerShutdownHook();  
  15.      }  
  16.  }  

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

我们来看一下结果:

现在开始初始化容器
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实现类构造器!!
BeanFactoryPostProcessor调用postProcessBeanFactory方法
这是BeanPostProcessor实现类构造器!!
这是InstantiationAwareBeanPostProcessorAdapter实现类构造器!!
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调用postProcessBeforeInstantiation方法
【构造器】调用Person的构造器实例化
InstantiationAwareBeanPostProcessor调用postProcessPropertyValues方法
【注入属性】注入属性address
【注入属性】注入属性name
【注入属性】注入属性phone
【BeanNameAware接口】调用BeanNameAware.setBeanName()
【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()
BeanPostProcessor接口方法postProcessBeforeInitialization对属性进行更改!
【InitializingBean接口】调用InitializingBean.afterPropertiesSet()
【init-method】调用<bean>的init-method属性指定的初始化方法
BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改!
InstantiationAwareBeanPostProcessor调用postProcessAfterInitialization方法
容器初始化成功
Person [address=广州, name=张三, phone=110]
现在开始关闭容器!
【DiposibleBean接口】调用DiposibleBean.destory()
【destroy-method】调用<bean>的destroy-method属性指定的初始化方法

转载:http://www.cnblogs.com/zrtqsk/p/3735273.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值