生命周期,很熟悉的字眼,比如面试官问你:servlet的生命周期简单的说下,然后噼里啪啦的说一大堆。
生命周期无非就是初始化、使用、销毁是吧,那当然Bean的生命周期也是如此。
那怎么管理Bean的生命周期呢? 点个赞,往下看,嘿嘿嘿~~
方式一:在配置Bean的时候,通过设置init-method和destory-method来指定初始化和销毁的方法。
方式二:实现BeanPostProcessor接口,实现初始化和销毁的方法,这个是针对全部的Bean。
方式一实现:
依旧依旧使用我们的Car对象,新增初始化、销毁的方法,大概看下两个方法就行了。
/**
* 汽车类
*/
public class Car {
/**
* 汽车品牌
*/
private String brand;
/**
* 汽车产地
*/
private String origin;
/**
* 汽车价格
*/
public int price;
public void setBrand(String brand) {
this.brand = brand;
}
public void setOrigin(String origin) {
this.origin = origin;
}
public void setPrice(int price) {
this.price = price;
}
/**
* 初始化方法
*/
public void init(){
System.out.println("Car init method .....");
}
/**
* 销毁方法
*/
public void destory(){
System.out.println("Car destory method .....");
}
@Override
public String toString() {
return "Car{" +
"brand='" + brand + '\'' +
", origin='" + origin + '\'' +
", price=" + price +
'}';
}
}
Bean的xml配置,炒鸡简单的啦~
方式二实现:
新建一个java文件,实现BeanPostProcessor接口,并实现两个方法,并且需要配置到IOC容器中
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class MyBean implements BeanPostProcessor {
/**
* 该init-method之前被调用
* @param o
* @param beanName
* @return
* @throws BeansException
*/
public Object postProcessBeforeInitialization(Object o, String beanName) throws BeansException {
//打印
System.out.println("postProcessBeforeInitialization ---->"+beanName );
//这里是针对全部的Bean初始化时都会到这里,可以使用if判断需要处理的bean
//最后需要把该Bean对象返回出去
return o;
}
/**
* init-method之后被调用
* @param o
* @param beanName
* @return
* @throws BeansException
*/
public Object postProcessAfterInitialization(Object o, String beanName) throws BeansException {
//打印
System.out.println("postProcessAfterInitialization ---->"+beanName );
//最后需要把该Bean对象返回出去
return o;
}
}
最后运行结果: 有疑问吗?如果感觉到有疑问可以评论,小编看到会回复的!!!
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-five.xml");
Car people = (Car)ctx.getBean("car");
//关闭ioc容器,这个对象才有IOC容器关闭的方法ClassPathXmlApplicationContext
ctx.close();
}
十月 30, 2018 11:28:44 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@246b179d: startup date [Tue Oct 30 23:28:44 CST 2018]; root of context hierarchy
十月 30, 2018 11:28:44 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext-five.xml]
postProcessBeforeInitialization ---->car
Car init method .....
postProcessAfterInitialization ---->car
十月 30, 2018 11:28:44 下午 org.springframework.context.support.ClassPathXmlApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@246b179d: startup date [Tue Oct 30 23:28:44 CST 2018]; root of context hierarchy
Car destory method .....