1.car类
package com.hxzy.cycle;
public class Car {
private String brand;
public Car() {
System.out.println("构造器运行");
}
public void setBrand(String brand) {
System.out.println("set方法调用");
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 + "]";
}
}
2.后置处理器类
package com.hxzy.cycle;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class MyBeanPostProcess implements BeanPostProcessor {
//在init-method方法之后被调用
// bean: bean 实例本身
// beanName: IOC容器配置的bean的名字
// 返回值:是实际上返回给用户的那个bean,可以在重新的方法中修改返回值。
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("在初始化方法之后 后置处理器 : " + bean + ", " + beanName);
//偷梁换柱,添加此处代码后,输出中直接将朗逸换为途观
Car car = new Car();
car.setBrand("途观");
return car;
// return bean;
}
//在init-method方法之前被调用
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("在初始化方法之前 后置处理器 : "+ bean + ", " + beanName);
if ("car".equals(beanName)) {
System.out.println("啥也不做");
}
return bean;
}
}
3.bean配置类
<?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.hxzy.cycle.Car"
init-method="init"
destroy-method="destory">
<property name="brand" value="朗逸"> </property>
</bean>
<!-- 配置bean的后置处理器 -->
<bean class="com.hxzy.cycle.MyBeanPostProcess"></bean>
</beans>
4.测试类
package com.hxzy.cycle;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestBeanCycle {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("cycle.xml");
Car car = (Car) ctx.getBean("car");
System.out.println(car);
ctx.close();
}
}
运行效果
信息: Loading XML bean definitions from class path resource [cycle.xml]
构造器运行
set方法调用
在初始化方法之前 后置处理器 : Car [brand=朗逸], car
啥也不做
init方法
在初始化方法之后 后置处理器 : Car [brand=朗逸], car
构造器运行
set方法调用
Car [brand=途观]
十月 08, 2015 3:36:05 下午 org.springframework.context.support.AbstractApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@117ae12: startup date [Thu Oct 08 15:36:05 CST 2015]; root of context hierarchy
destory方法