spring 容器中的bean的完整生命周期一共分為十一步完成。
1.bean對象的實例化
2.封裝屬性,也就是設置properties中的屬性值
3.如果bean實現了BeanNameAware,則執行setBeanName方法,也就是bean中的id值
4.如果實現BeanFactoryAware或者ApplicationContextAware ,需要設置setBeanFactory或者上下文對象setApplicationContext
5.如果存在類實現BeanPostProcessor后處理bean,執行postProcessBeforeInitialization,可以在初始化之前執行一些方法
6.如果bean實現了InitializingBean,則執行afterPropertiesSet,執行屬性設置之后的操作
7.調用<bean init-method="">執行指定的初始化方法
8.如果存在類實現BeanPostProcessor則執行postProcessAfterInitialization,執行初始化之后的操作
9.執行自身的業務方法
10.如果bean實現了DisposableBean,則執行spring的的銷毀方法
11.調用<bean destory-method="">執行自定義的銷毀方法。
第五步和第八步可以結合aop,在初始化執行之前或者執行之后執行一些操作。
以上就是springbean的完整生命周期.
代碼如下:
public class Man implements BeanNameAware, ApplicationContextAware, InitializingBean, DisposableBean {
private String name;
public Man() {
System.out.println("第一步:實例化類");
}
public void setName(String name) {
System.out.println("第二步:設置屬性");
this.name = name;
}
@Override
public void setBeanName(String s) {
System.out.println("第三步:設置bean的名稱也就是spring容器中的名稱,也就是id值" + name);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("第四步:了解工廠信息ApplicationContext");
}
//第五步執行初始化之前執行的方法
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("第六步:屬性設置后執行的方法");
}
public void setup() {
System.out.println("第七步:執行自己配置的初始化方法");
}
//第八步執行初始化之后執行的方法
public void run() {
System.out.println("第九步:執行自身的業務方法");
}
@Override
public void destroy() throws Exception {
System.out.println("第十步:執行spring的銷毀方法");
}
public void destory() {
System.out.println("第十一步:執行自己配置的銷毀方法");
}
}
指定的類實現了BeanPostProcessor
public class MyBeanPostProcess implements BeanPostProcessor {
//后處理bean,最重要的兩步
@Override
public Object postProcessBeforeInitialization(Object bean, String s) throws BeansException {
System.out.println("第五步:初始化之前執行的方法");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String s) throws BeansException {
System.out.println("第八步:執行初始化之后的方法");
return bean;
}
}
applicationContext.xml中的配置
<bean id="man" class="com.itheima.ioc.springBeanlife.Man" init-method="setup" destroy-method="destory">
<property name="name" value="張三"/>
</bean>
<bean class="com.itheima.ioc.springBeanlife.MyBeanPostProcess"/>
測試
@Test
public void beanlifeTest(){
ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
Man man=(Man)context.getBean("man");
man.run();
context.close();
}