spring bean 的初始化流程

spring bean的初始化流程按照以下顺序走:

1.执行 构造方法。

一般为无参,下面为有参时的配置

  1. <bean id="user" class="kevin.User">    
  2.     <constructor-arg value="123"></constructor-arg>    
  3.     <constructor-arg value="male"></constructor-arg>    
  4.     <property name="name" value="Kevin"></property>    
  5.     <property name="age" value="99"></property>    
  6. </bean> 

2.执行 setter方法。

3.执行实现了aware接口的相关方法(可能有多个aware方法)

4.init方法前后

   (1) BeanPostProcessor的postProcessorBeforeInitialization方法

  (2)InitializingBean 的 afterPropertiesSet() 方法 (接口)

  (3) init-method 方法 (xml 文件里)

  1. <bean id="helloWorld" class="com.spring.lifecycle.HelloWorld"  
  2.         init-method="customInit" destroy-method="customDestroy">  
  3.         <property name="hello" value="hello world!"></property>  
  4.     </bean>  

   (4) BeanPostProcessor的postProcessorAfterInitialization方法

 

以上几步,可以全没有,可以有其中的几步,但是整体的执行顺序是自上而下的,就跟web.xml执行道理一样。

 

重点说下第3步,该步中有可以细分各个aware 方法,顺序为:

(1) BeanNameAware接口的 setBeanName() 方法。

(2) BeanClassLoaderAware 接口的 setBeanClassLoader() 方法。

(3) BeanFactoryAware 接口的 setBeanFactory() 方法。

(4) ResourceLoader接口的 set...() 方法。(ApplicationContext使用)

(5) ApplicationEventPublisherAware 接口的 set...() 方法。(ApplicationContext使用)

(6) MessageSourceAware 接口的 set...() 方法。(ApplicationContext使用)

(5) ApplicationContextAware 接口的 set...() 方法。(ApplicationContext使用)

(6) ServletContextAware 接口的 set...() 方法。(WebApplicationContext使用,仅对web有用)

 

以上这几小步也是按照顺序执行的,可以全有,可以全没有,也可以有其中的一步或几步

 

spring框架自己的实现类就是按照这种流程走的。

spring框架就几个核心的接口,然后大部分都是实现类,来实现这一个或多个核心接口。

猜你喜欢

转载自huttoncs.iteye.com/blog/2244285