Spring中Bean初始化实例【重要】

参考文章:

Spring Bean 生命周期

Spring容器-Bean的生命周期 

Spring开闭原则的表现-BeanPostProcessor扩展点-1

 

容器启动时

最先调用

        BeanFactoryPostProcessor

                        ->postProcessBeanFactory() 

 

getBean时

实例化之后调用

        InstantiationAwareBeanPostProcessor

                ->postProcessPropertyValues()

 

初始化时

        属性注入(setter)

 

        BeanNameAware

                ->setBeanName() 

        BeanFactoryAware

                ->setBeanFactory() 

        ApplicationContextAware

                ->setApplicationContext()

  

        BeanPostProcessor

               ->postProcessBeforeInitialization()

        InitializingBean

                ->afterPropertiesSet()

        init-method属性

        BeanPostProcessor

                ->postProcessAfterInitialization()

 

        DiposibleBean

                ->destory() 

        destroy-method属性

 

 

Java代码   收藏代码
  1. BeanFactoryPostProcessor   
  2.     //Spring IoC容器允许BeanFactoryPostProcessor在容器实际实例化任何其它的bean之前读取配置元数据,并有可能修改它。  
  3.     //同时BeanFactoryPostProcessor的回调比BeanPostProcessor要早  
  4.     void postProcessBeanFactory(ConfigurableListableBeanFactory arg)      
  5.   
  6.       
  7. InstantiationAwareBeanPostProcessorAdapter   
  8.     其适配器类:InstantiationAwareBeanPostProcessor   
  9.       
  10.     //实例化Bean之前调用 (Bean构造函数前)  
  11.     Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName)  
  12.       
  13.     //实例化Bean之后调用   
  14.     boolean postProcessAfterInstantiation(Object bean, String beanName)  
  15.           
  16.     PropertyValues postProcessPropertyValues(PropertyValues pvs,    
  17.             PropertyDescriptor[] pds, Object bean, String beanName)   
  18.       
  19.       
  20. BeanPostProcessor   
  21.     //实例化、依赖注入完毕,在初始化之前调用,完成一些定制的初始化任务    
  22.     Object postProcessBeforeInitialization(Object bean, String beanName)  
  23.       
  24.     //实例化、依赖注入、初始化完毕时执行    
  25.     Object postProcessAfterInitialization(Object bean, String beanName)   

 BeanFactoryPostProcessor和BeanPostProcessor都是Spring初始化bean的扩展点。两个接口非常相似。

BeanFactoryPostProcessor可以在postProcessBeanFactory()中对bean的定义(配置元数据)进行处理,而BeanPostProcessor不可以。

同时BeanFactoryPostProcessor的回调比BeanPostProcessor要早。

 http://blog.csdn.net/mn11201117/article/details/24986325

http://blog.csdn.net/xiao_jun_0820/article/details/7242379

 

实例1:

百度文库:

spring bean的生命周期是怎样的

  

实例2(重要):

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个接口,

【对于BeanFactoryAware和BeanNameAware接口,第一个接口让bean感知容器(即BeanFactory实例,从而以此获取该容器配置的其他bean对象),而后者让bean获得配置文件中对应的配置名称。在一般情况下用户不需要关心这两个接口。如果bean希望获得容器中的其他bean,可以通过属性注入的方式引用这些bean。如果bean希望在运行期获知在配置文件中的Bean名称,可以简单的将名称作为属性注入

综上所述,我们认为除非编写一个基于spring之上的扩展框架插件或者子项目之类的东西,否则用户完全可以抛开以上4个bean生命周期的接口类

 

但BeanPostProcessor接口却不一样,它不要求bean去继承它,它可以完全像插件一样注册到spring容器中,为容器提供额外的功能。spring充分利用了BeanPostProcessor对bean进行加工处理(SpringAOP以此为基础)

 

同时有2个方法,对应配置文件中<bean>的init-method和destroy-method。如下:

 

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

  

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

 

Java代码   收藏代码
  1. package springBeanTest;  
  2.    
  3.  import org.springframework.beans.BeansException;  
  4.  import org.springframework.beans.factory.config.BeanPostProcessor;  
  5.    
  6.  public class MyBeanPostProcessor implements BeanPostProcessor {  
  7.    
  8.      public MyBeanPostProcessor() {  
  9.         super();  
  10.         System.out.println("这是BeanPostProcessor实现类构造器!!");           
  11.     }  
  12.   
  13.     @Override  
  14.     public Object postProcessAfterInitialization(Object arg, String arg)  
  15.             throws BeansException {  
  16.         System.out.println("BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改!");  
  17.         return arg;  
  18.     }  
  19.   
  20.     @Override  
  21.     public Object postProcessBeforeInitialization(Object arg, String arg)  
  22.             throws BeansException {  
  23.         System.out.println("BeanPostProcessor接口方法postProcessBeforeInitialization对属性进行更改!");  
  24.         return arg;  
  25.     }  
  26. }  

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

  

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

 

Java代码   收藏代码
  1. package springBeanTest;  
  2.    
  3.  import java.beans.PropertyDescriptor;    
  4.  import org.springframework.beans.BeansException;  
  5.  import org.springframework.beans.PropertyValues;  
  6.  import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;  
  7.    
  8.  public class MyInstantiationAwareBeanPostProcessor extends  
  9.         InstantiationAwareBeanPostProcessorAdapter {  
  10.   
  11.     public MyInstantiationAwareBeanPostProcessor() {  
  12.         super();  
  13.         System.out.println("这是InstantiationAwareBeanPostProcessorAdapter实现类构造器!!");  
  14.     }  
  15.   
  16.     // 接口方法、实例化Bean之前调用  
  17.     @Override  
  18.     public Object postProcessBeforeInstantiation(Class beanClass,  
  19.             String beanName) throws BeansException {  
  20.        
  21.         System.out.println("InstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation方法");  
  22.         return null;  
  23.     }  
  24.   
  25.     // 接口方法、实例化Bean之后调用  
  26.     @Override  
  27.     public Object postProcessAfterInitialization(Object bean, String beanName)  
  28.             throws BeansException {  
  29.         System.out.println("InstantiationAwareBeanPostProcessor调用postProcessAfterInitialization方法");  
  30.         return bean;  
  31.     }  
  32.   
  33.     // 接口方法、设置某个属性时调用  
  34.     @Override  
  35.     public PropertyValues postProcessPropertyValues(PropertyValues pvs,  
  36.             PropertyDescriptor[] pds, Object bean, String beanName)  
  37.             throws BeansException {  
  38.         System.out.println("InstantiationAwareBeanPostProcessor调用postProcessPropertyValues方法");  
  39.         return pvs;  
  40.     }  
  41. }  

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

  

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

 

Java代码   收藏代码
  1. package springBeanTest;  
  2.    
  3.  import org.springframework.beans.BeansException;  
  4.  import org.springframework.beans.factory.config.BeanDefinition;  
  5.  import org.springframework.beans.factory.config.BeanFactoryPostProcessor;  
  6.  import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;  
  7.    
  8.  public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {  
  9.    
  10.     public MyBeanFactoryPostProcessor() {  
  11.         super();  
  12.         System.out.println("这是BeanFactoryPostProcessor实现类构造器!!");  
  13.     }  
  14.   
  15.     @Override  
  16.     public void postProcessBeanFactory(ConfigurableListableBeanFactory arg)  
  17.             throws BeansException {  
  18.         System.out  
  19.                 .println("BeanFactoryPostProcessor调用postProcessBeanFactory方法");  
  20.         BeanDefinition bd = arg.getBeanDefinition("person");  
  21.         bd.getPropertyValues().addPropertyValue("phone""");  
  22.     }   
  23. }  

 

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

 

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.    
  3. <beans xmlns="http://www.springframework.org/schema/beans"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  5.     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xsi:schemaLocation="  
  7.             http://www.springframework.org/schema/beans   
  8.             http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">  
  9.    
  10.     <bean id="beanPostProcessor" class="springBeanTest.MyBeanPostProcessor"></bean>  
  11.    
  12.     <bean id="instantiationAwareBeanPostProcessor" class="springBeanTest.MyInstantiationAwareBeanPostProcessor"></bean>  
  13.    
  14.     <bean id="beanFactoryPostProcessor" class="springBeanTest.MyBeanFactoryPostProcessor">  
  15.     </bean>  
  16.       
  17.     <bean id="person" class="springBeanTest.Person" init-method="myInit"  
  18.         destroy-method="myDestory" scope="singleton" p:name="张三" p:address="广州"  
  19.         p:phone="15900000000" />   
  20. </beans>  

 

6.测试 

Java代码   收藏代码
  1. package springBeanTest;  
  2.    
  3.  import org.springframework.context.ApplicationContext;  
  4.  import org.springframework.context.support.ClassPathXmlApplicationContext;  
  5.    
  6.  public class BeanLifeCycle {  
  7.    
  8.      public static void main(String[] args) {  
  9.    
  10.         System.out.println("现在开始初始化容器");  
  11.           
  12.         ApplicationContext ctx = new ClassPathXmlApplicationContext("springBeanTest/beans.xml");  
  13.         System.out.println("容器初始化成功");      
  14.    
  15.         //得到Preson,并使用  
  16.         Person person = ctx.getBean("person",Person.class);  
  17.         System.out.println(person);  
  18.           
  19.         System.out.println("现在开始关闭容器!");  
  20.         ((ClassPathXmlApplicationContext)ctx).registerShutdownHook();  
  21.     }  
  22. }  

 

结果如下:

现在开始初始化容器

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属性指定的初始化方法 

 

图示如下:

猜你喜欢

转载自zh-ka-163-com.iteye.com/blog/2232957