Bean的生命周期
Bean的生命周期:创建(new …)、初始化(赋初值)、 …、销毁
本文讲解的是Bean的初始化和销毁方法,类似于serverlet !
方法1:直接在对应的实体类中写初始化,销毁方法,然后IOC容器中指定。
package entity;
public class Student {
......
public void myInit(){
System.out.println("init......");
}
public void myDestroy(){
System.out.println("destroy......");
}
......
}
xml指定的方式:给init-method和destroy-method属性附上对应实体类中的方法名。
<bean id="XXX" class="entity.Student" init-method="myInit" destroy-method="myDestroy">
........
</bean>
配置类:也就是在@Bean注解中增加属性initMethod 和 destroyMethod 。
@Bean(value="xxx",initMethod = "myInit",destroyMethod = "myDestroy")
public Student myStudent(){
Student xxx= new Student(1,"zs");
return xxx;
}
方法2:利用JSR250规范的两个注解:@PostConstruct和@PreDestroy
注:此方法必须得依靠三层注解+扫描器的方式
示例:
@Component(value = "myConverter")
public class MyIntToStringConverter {
//(JSR:java规范 提供的两个注解)
@PostConstruct
public void init(){
System.out.println("转换..init...");
}
public void myConverter(){
System.out.println("转换....");
}
@PreDestroy
public void destroy(){
System.out.println("销毁...destroy");
}
}
方法3:实现DisposableBean和InitializingBean接口,并重写里面的方法
注:此方法必须得依靠三层注解+扫描器的方式
package luzelong.converter;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
@Component
public class MyFunction implements InitializingBean, DisposableBean {
public void myMethod(){
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("MyFunction...init...");
}
@Override
public void destroy() throws Exception {
System.out.println("MyFunction...destroy...");
}
}
方法4:实现BeanPostProcessor接口并重写里面的方法
注:此方法必须得依靠三层注解+扫描器的方式
注:该方法实现的是容器中所有bean的初始化和销毁,这一点有别于上面的三个方法
package luzelong.converter;
import entity.Student;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
//该接口是给容器的所有Bean加初始化、销毁
@Component
public class MyXxx implements BeanPostProcessor {//该接口的功能是拦截Ioc容器的所有bean,并且可以进行bean的初始化、销毁操作 执行时机是在实例化bean之后
@Override
public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
if(o instanceof Student){//这就是该接口的强大之处:偷梁换柱
System.out.println("初始化:"+s+":"+o);
System.out.println("MyXxx...初始化");
Student stu = (Student)o;
stu.setStuname("zs123456");
stu.setStuno(123);
return stu;
}
return o;
}
@Override
public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
if(o instanceof Student) {
System.out.println("销毁:" + s + ":" + o);
System.out.println("MyXxx...销毁");
}
return o;
}
}
以上就是spring的初始,销毁。