实体Bean:
Car.java:
package spring.beans.cycle; public class Car { private String name; private int price; public Car() { super(); System.out.println("Constructor..."); } public void init(){//init-method System.out.println("init..."); } public void destroy(){//destroy-method System.out.println("destroy..."); } public String getName() { return name; } public void setName(String name) { System.out.println("setName..."); this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { System.out.println("setPrice..."); this.price = price; } @Override public String toString() { return "Car [name=" + name + ", price=" + price + "]"; } }
Spring的配置文件核心代码添加:
<bean id="car" class="spring.beans.cycle.Car" p:name="奥迪" p:price="300000" init-method="init" destroy-method="destroy"> </bean>
实现BeanPostProcessor接口,并具体提供两个方法的实现
postProcessAfterInitialization:init-method方法之后调用,
postProcessBeforeInitialization:init-method方法之前调用,
两个参数:
bean:bean实例本身
beanName:IOC容器配置的bean的名字
返回值:是实际上返回给用户的bean,注意:可以在上面两个方法中修改bean,甚至返回一个新的bean。
MyBeanPostProcessor.java:
package spring.beans.cycle; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; public class MyBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("postProcessAfterInitialization"+bean+","+beanName); if("...".equals(beanName)){ //... } Car car=new Car(); car.setName("福特"); return car; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("postProcessBeforeInitialization"+bean+","+beanName); Car car=new Car(); car.setName("长安"); return car; } }
把这个类配置到spring容器中:
<!-- 配置bean的后置处理器 --> <bean class="spring.beans.cycle.MyBeanPostProcessor"></bean>
测试方法:
package spring.beans.cycle.test; import org.springframework.context.support.ClassPathXmlApplicationContext; import spring.beans.cycle.Car; public class Main { public static void main(String[] args) { ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("beans-cycle.xml"); Car car=(Car) ctx.getBean("car"); System.out.println(car); ctx.close(); } }
输出:
Constructor... setName... setPrice... postProcessBeforeInitializationCar [name=奥迪, price=300000],car Constructor... setName... init... postProcessAfterInitializationCar [name=长安, price=0],car Constructor... setName... Car [name=福特, price=0] 四月 13, 2017 3:46:13 下午 org.springframework.context.support.ClassPathXmlApplicationContext doClose 信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@3f91beef: startup date [Thu Apr 13 15:46:13 CST 2017]; root of context hierarchy destroy...