Spring @PostConstruct和@PreDestroy實例
在Spring中,既可以實現 InitializingBean和DisposableBean接口或在bean配置文件中指定 init-method 和 destroy-method 在初始化和銷燬回調函數。在這篇文章中,我們將介紹如何使用 @PostConstruct 和 @PreDestroy 註解來做同樣的事情。
注:@PostConstruct和@PreDestroy 標註不屬於 Spring,它是在J2EE庫- common-annotations.jar。
@PostConstruct 和 @PreDestroy
一個 CustomerService Bean使用 @PostConstruct 和 @PreDestroy 註釋
package com.yiibai.customer.services;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public class CustomerService
{
String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@PostConstruct
public void initIt() throws Exception {
System.out.println("Init method after properties are set : " + message);
}
@PreDestroy
public void cleanUp() throws Exception {
System.out.println("Spring Container is destroy! Customer clean up");
}
}
默認情況下,Spring不會意識到@PostConstruct和@PreDestroy註解。要啓用它,要麼註冊「CommonAnnotationBeanPostProcessor」,要麼在bean配置文件的<context:annotation-config />‘ 指定,
1. CommonAnnotationBeanPostProcessor
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
<bean id="customerService" class="com.yiibai.customer.services.CustomerService">
<property name="message" value="i'm property message" />
</bean>
2. <context:annotation-config />
<context:annotation-config />
<bean id="customerService" class="com.yiibai.customer.services.CustomerService">
<property name="message" value="i'm property message" />
</bean>
執行結果
package com.yiibai.common;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.yiibai.customer.services.CustomerService;
public class App
{
public static void main( String[] args )
{
ConfigurableApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});
CustomerService cust = (CustomerService)context.getBean("customerService");
System.out.println(cust);
context.close();
}
}
輸出結果
Init method after properties are set : im property message
com.yiibai.customer.services.CustomerService@47393f
...
INFO: Destroying singletons in org.springframework.beans.factory.
support.DefaultListableBeanFactory@77158a:
defining beans [customerService]; root of factory hierarchy
Spring Container is destroy! Customer clean up
initIt()方法(@PostConstruct)被調用時,消息屬性設置後 cleanUp() 方法(@PreDestroy)是在context.close()執行後被調用;
下載源代碼 – http://pan.baidu.com/s/1qX2W6xI