大家中午好啊!我们今天来聊聊spring之管理bean的生命周期吧!
1,创建一个类:
public class Car {
private String brand;
public Car() {
System.out.println("Car.constructor 构造器");
}
@Override
public String toString() {
return "Car [brand=" + brand + "]";
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
System.out.println("setBrand");
this.brand = brand;
}
public void one() {
System.out.println("init.......");
}
public void last() {
System.out.println("destory......");
}
}
2,配置xml:
<bean>
destroy-method="last">
<property>
/<bean>
< !-- 配置bean的后置处理器 ,不需要配置id,IOC容器会自动识别
实现BeanPostProcessor接口,并提供
postProcessBeforeInitialization:init-method之前调用
postProcessAfterInitialization:destroy-method之后调用
bean:bean的实例;
beanName:IOC容器配置的bean的ID的名称
返回值:实际返回给用户的那个bean,不过可以在以上两个方法中修改bean
-->
<bean>
3,写主函数:
public class Cycle {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("bean-cycle.xml");
Car car = (Car) ctx.getBean("car");
System.out.println(car);
ctx.close();
}
}
4,创建bean的后置处理器:
public class MybeanProfessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization " +bean+ ","+beanName);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessAfterInitialization " +bean+ ","+beanName);
Car car =new Car();
car.setBrand("Ford");
return car;
}
}
5,spring IOC管理bean生命周期的过程:
(1)通过构造器或着工厂创建bean实例
(2)为bean设置属性或着引用其它bean
(3)调用postProcessBeforeInitialization方法
(4)调用bean的初始化方法
(5)调用postProcessAfterInitialization方法
(6)使用bean
(7)关闭容器后调用destroy方法
今天的内容希望大家会喜欢!求关注哦!另外,更多精彩内容请关注尚学堂!
閱讀更多 火到沒朋友的大數據 的文章
關鍵字: XML