Spring IOC可以管理bean的生命周期,Spring 允许在bean的生命周期特定点执行定制的任务。
Bean的后置处理器
- Bean的后置处理器允许在调用初始化方法前后对Bean进行额外的处理。
- Bean后置处理器对IOC里的所有Bean实例逐一处理,而非单一实例。典型应用:检查Bean属性的正确性或根据特定的标准更改Bean的属性。
- 对Bean的后置处理器而言,需要实现接口BeanPostProcessor
Spring IOC对bean的生命周期管理过程:
- 通过构造器或者工厂方法创建实例
- 为bean的属性设和其他bean的引用
- 调用后置处理器的postProcessBeforeInitialization方法
- 调用bean的初始化方法
- 调用后置处理器的postProcessAfterInitialization方法
- Bean可以使用了
- 当容器关闭时,调用bean的销毁方法
在Bean的声明里设置init-method和destory-method属性,为bean指定初始化和销毁方法。
例子
beans-cycle.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.spring.test.cycle.Car" init-method="init" destroy-method="destory">
<property name="brand" value="Audi"></property>
</bean>
<!-- 配置bean的后置处理器 -->
<bean class="com.spring.test.cycle.MyBeanPostProcessor"></bean>
</beans>
Car.java
package com.spring.test.cycle;
public class Car {
private String brand;
public Car() {
System.out.println("Car constructor...");
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
System.out.println("setBrand:" + brand);
this.brand = brand;
}
public void init() {
System.out.println("car init...");
}
public void destory() {
System.out.println("car destory...");
}
}
MyBeanPostProcessor.java
package com.spring.test.cycle;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
/**
* 后置处理实现类
* @author cye
*
*/
public class MyBeanPostProcessor implements BeanPostProcessor {
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("postProcessAfterInitialization:" + bean + ", " + beanName);
if ("car".equals(beanName)) {
// 处理
}
return bean;
}
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("postProcessAfterInitialization:" + bean + ", " + beanName);
Car car = new Car();
car.setBrand("Falali");
bean = car;
return bean;
}
}
Main.java
package com.spring.test.cycle;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-cycle.xml");
Car car = (Car) ctx.getBean("car");
System.out.println(car);
car.destory();
}
}