在配置bean的时候指定 bean的初始化方法和析构函数。
下面的例子展示了从Ioc容器创建到创建bean实例到Ioc容器销毁的过程。
配置文件如下:
<bean id="flowerBean2" class="com.pfSoft.spel.Flower" init-method="testInitFun" destroy-method="testDestory"> <property name="flowerName" value="rose"></property> <property name="color" value="red"></property> <property name="price" value="20"></property> </bean>
将原实体类改写,在构造函数、属性赋值、中增加out输出,方便查看先后顺序,并新增init和destory方法:
public class Flower {
private String flowerName;
private Double price;
/**
*
* @return the flowerName
*/
public String getFlowerName() {
return flowerName;
}
/**
* @param flowerName the flowerName to set
*/
public void setFlowerName(String flowerName) {
System.out.println("这里执行属性的set方法,setFlowName");
this.flowerName = flowerName;
}
private String color;
/**
*
* @return the color
*/
public String getColor() {
return color;
}
/**
* @param color the color to set
*/
public void setColor(String color) {
System.out.println("这里执行属性的set方法,setcolor");
this.color = color;
}
/**
*
* @return the price
*/
public Double getPrice() {
return price;
}
/**
* @param price the price to set
*/
public void setPrice(Double price) {
this.price = price;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Flower [flowerName=" + flowerName + ", price=" + price
+ ", color=" + color + "]";
}
private Flower(){
System.out.println("这里执行构造函数");
}
private void testInitFun() {
System.out.println("这里执行初始化方法");
}
private void testDestory() {
System.out.println("这里执行destory方法");
}
}
测试代码如下:
ApplicationContext applicationContext;
@Before
public void init() {
applicationContext = new ClassPathXmlApplicationContext(
"spring-SpEL.xml");
}
@Test
public void testFlower() {
Flower flower = (Flower) applicationContext.getBean("flowerBean2");
System.out.println(flower);
}
@After
public void after() {
ClassPathXmlApplicationContext context = (ClassPathXmlApplicationContext) applicationContext;
context.close();
}
输出结果为:
这里执行构造函数 这里执行属性的set方法,setFlowName 这里执行属性的set方法,setcolor 这里执行初始化方法 Flower [flowerName=rose, price=20.0, color=red] 四月 26, 2016 10:19:33 下午 org.springframework.context.support.ClassPathXmlApplicationContext doClose 信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@1637f22: startup date [Tue Apr 26 22:19:33 CST 2016]; root of context hierarchy 这里执行destory方法
由此可见执行先后顺序为 bean的构造函数——》set方法——》配置bean时指定的init-method方法——》销毁时,bean中配置指定的destroy-method方法
需要实现BeanPostProcessor接口,并且这个处理器是针对所有bean的。
原文:http://www.cnblogs.com/falcon-fei/p/5437170.html