Bean 的生命周期
Bean 的生命周期
生命周期:定义,初始化,使用,销毁
一.初始化
方法1
实现org.springframework.beans.foctory.InitializingBean接口,覆盖afterPropertiesSet方法。系统会自动查找afterPropertiesSet方法,执行其中的初始化操作
方法2
配置init-method,例如设置bean中init-method="init"那么在初始化过程中就会调用相应class指定类的init()方法进行初始化工作
<bean id="examInitBean" class="boy.ExamInitBean" init-method="init"/>
方法
public class ExamInitBean{
public void init(){
//init method
}
}
二 销毁(与初始化类似)
方法1
实现org.springframework.beans.foctory.DisposableBean,覆盖destory方法。
方法2
方法2.配置destory-method
<bean id="examDestoryBean" class="net.boy.spring.ExamDestoryBean" init-method="cleanup"/>
方法
public class ExamDestoryBean{
public void cleanup(){
//cleanup method
}
}
三 配置全局初始化、销毁方法
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
default-init-method="defautInit" default-destroy-method="defaultDestroy">
</beans>
测试
实现类
package boy.lifecycle;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class BeanLifeCycle implements InitializingBean, DisposableBean {
public void defautInit() {
System.out.println("Bean defautInit.");
}
public void defaultDestroy() {
System.out.println("Bean defaultDestroy.");
}
@Override
public void destroy() throws Exception {
System.out.println("Bean destroy.");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Bean afterPropertiesSet.");
}
public void start() {
System.out.println("Bean start .");
}
public void stop() {
System.out.println("Bean stop.");
}
}
测试类
packageboy.lifecycle;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import net.boy.spring.UnitTestBase;
@RunWith(BlockJUnit4ClassRunner.class)
public class TestBeanLifecycle extends UnitTestBase {
public TestBeanLifecycle() {
super("classpath:spring-lifecycle.xml");
}
@Test
public void test1() {
super.getBean("beanLifeCycle");
}
}
配置xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
default-init-method="defautInit" default-destroy-method="defaultDestroy">
<bean id="beanLifeCycle" class="net.boy.spring.lifecycle.BeanLifeCycle" init-method="start" destroy-method="stop"></bean>
</beans>
最后由 不一样的少年 编辑于2016年12月10日 20:33