在传统的Java应用中,Bean的生命周期非常简单。Java的关键词new用来实例化Bean(或许他是非序列化的)。这样就够用了。相反,Bean 的生命周期在Spring容器中更加细致。理解Spring Bean的生命周期非常重要,因为你或许要利用Spring提供的机会来订制Bean的创建过程。
1. 容器寻找Bean的定义信息并且将其实例化。
2.受用依赖注入,Spring按照Bean定义信息配置Bean的所有属性。
3.如果Bean实现了BeanNameAware接口,工厂调用Bean的setBeanName()方法传递Bean的ID。
4.如果Bean实现了BeanFactoryAware接口,工厂调用setBeanFactory()方法传入工厂自身。
5.如果BeanPostProcessor和Bean关联,那么它们的postProcessBeforeInitialzation()方法将被调用。
6.如果Bean指定了init-method方法,它将被调用。
7.最后,如果有BeanPsotProcessor和Bean关联,那么它们的postProcessAfterInitialization()方法将被调用。
到这个时候,Bean已经可以被应用系统使用了,并且将被保留在Bean Factory中知道它不再需要。
测试代码:
package com.spring.init;
/**
* 初始化顺序
*/
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;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class HelloWorld implements BeanNameAware,BeanFactoryAware, BeanPostProcessor,InitializingBean,DisposableBean{
private String hello;
public void setBeanName(String arg0) {
System.out.println("调用BeanNameAware的setBeanName()..." );
}
public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
System.out.println("调用setHello()..." );
}
public void customInit() {
System.out.println("调用customInit()...");
}
public void customDestroy() {
System.out.println("调用customDestroy()...");
}
public Object postProcessAfterInitialization(Object arg0, String arg1)
throws BeansException {
System.out.println("调用BeanPostProcessor的postProcessAfterInitialization()...");
return null;
}
public Object postProcessBeforeInitialization(Object arg0, String arg1)
throws BeansException {
System.out.println("调用BeanPostProcessor的postProcessBeforeInitialization()...");
return null;
}
public void destroy() throws Exception {
System.out.println("调用DisposableBean的destory()...");
}
public void afterPropertiesSet() throws Exception {
System.out.println("调用InitializingBean的afterPropertiesSet()...");
}
public void setBeanFactory(BeanFactory arg0) throws BeansException {
System.out.println("调用BeanFactoryAware的setBeanFactory()...");
}
}
XML:
<bean name="helloWorld" class="com.spring.init.HelloWorld" init-method="customInit" destroy-method="customDestroy" >
<property name="hello" value="hello world!"></property>
</bean>
结果:
调用setHello()...
调用BeanNameAware的setBeanName()...
调用BeanFactoryAware的setBeanFactory()...
调用InitializingBean的afterPropertiesSet()...
调用customInit()...
调用BeanPostProcessor的postProcessBeforeInitialization()...
调用BeanPostProcessor的postProcessAfterInitialization()...
调用BeanPostProcessor的postProcessBeforeInitialization()...
调用BeanPostProcessor的postProcessAfterInitialization()...
调用DisposableBean的destory()...
调用customDestroy()...