Spring IOC容器对Bean的生命周期进行管理的过程:
1)通过构造器或工厂方法创建Bean实例 2)为Bean的属性设置值和对其他Bean的引用 3)调用Bean的初始化方法 4)Bean可以使用了 5)当容器关闭时,调用Bean的销毁方法
可以在Bean的声明里设置init-method 和destory-method属性,为Bean指定初始化和销毁方法
创建bean后置处理器
Bean后置处理器允许在调用初始化方法前后对Bean进行额外的处理。对IOC容器里所有的Bean实例逐一处理,而非单一实例,典型的应用是:检查Bean属性的正确性或根据特定的标准更改Bean的属性
对Bean后置处理器而言,需要实现org.springframework.beans.factory.config.BeanPostProcessor
接口,在初始化方法被调用前后,Spring将把每个Bean实例分别传递给上述接口的两个方法:
public interface BeanPostProcessor {
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
添加Bean后置处理器后Bean的生命周期
1)通过构造器或工厂方法创建Bean实例 2)为Bean的属性设置值和对其他Bean的引用 3)将Bean实例传递给Bean后置处理器的postProcessBeforeInitialization 方法 4)调用Bean的初始化方法 5)将Bean实例传递给Bean后置处理器的postProcessAfterInitialization方法 6)Bean可以使用了 7)当容器关闭时,调用Bean的销毁方法
//applicationContext.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">
<bean id = "car" class="com.sangyu.test13.Car" init-method="init" destroy-method="destory">
<property name="brand" value="Audi"></property>
</bean>
<!--
实现BeanPostProcessor接口,并提供具体实现
postProcessBeforeInitialization,postProcessAfterInitialization
bean:bean实例本身
beanName:IOC容器配置的bean的名字
返回值:是实际上返回给用户的那个bean,可以返回一个新的bean
-->
<!-- 配置bean的后置处理器 -->
<bean class="com.sangyu.test13.MyBeanPostProcessor"></bean>
</beans>
// Car.java
public class Car {
public Car(){
System.out.println("Car's Constructor...");
}
private String brand;
public void setBrand(String brand){
System.out.println("setBrand...");
this.brand = brand;
}
public void init(){
System.out.println("init...");
}
public void destory(){
System.out.println("destory");
}
@Override
public String toString() {
return "Car{" +
"brand='" + brand + '\'' +
'}';
}
}
// Main.java
public class Main {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
Car car = (Car) ctx.getBean("car");
System.out.println(car);
// 关闭IOC容器
ctx.close();
}
}
// MyBeanPostProcessor.java
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization: " + beanName + ", " + beanName );
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessAfterInitialization: " + beanName + ", " + beanName);
Car car = new Car();
car.setBrand("Ford");
return car;
}
}