Spring作为当前Java最流行、最强大的轻量级框架,受到了程序员的热烈欢迎。准确的了解Spring Bean的生命周期是非常必要的。我们通常使用ApplicationContext作为Spring容器。这里,我们讲的也是 ApplicationContext中Bean的生命周期。而实际上BeanFactory也是差不多的,只不过处理器需要手动注册。
一、生命周期流程图:
Spring 从初始化bean或销毁bean时,有时需要做一些处理工作,因此spring建立和销毁bean的时候调用bean的两个生命周期方法
<!--Bean的作用范围-->
<bean id="person" class="com.coure.ioc.demo.Person" scope="prototype" init-method="init" destroy-method="destroy"></bean>
init-method:当bean被载入到容器的时候调用init
destroy-method:当bean从容器中删除的时候调用destroy(scope="prototype"有效)
1. 新建配置文件 》resources》applicationContext.xml
<bean id="man" class="com.coure.ioc.demo.Man" destroy-method="teardown"></bean>
2. 新建class文件 Man
package com.coure.ioc.demo;
public class Man {
public Man(){
System.out.println("小孩出生了....");
}
public void setup(){
System.out.println("小孩长大成年了....");
}
public void teardown(){
System.out.println("成年了已经老死了....");
}
}
3.3.新建class 文件 Spring 测试类
package com.coure.ioc.demo;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Spring {
@Test
public void ceshi(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Man man = (Man)applicationContext.getBean("man");
System.out.println(man);
((ClassPathXmlApplicationContext) applicationContext).close();
}
}
打印控制台显示
小孩出生了....
com.coure.ioc.demo.Man@4681c175
成年了已经老死了....
Disconnected from the target VM, address: '127.0.0.1:58038', transport: 'socket'
完整的生命周期