《Spring Recipes》第二章筆記:Customizing Bean Initiali...

《Spring Recipes》第二章筆記:Customizing Bean Initialization and Destruction


問題

用戶想要指定Spring容器在建立完一個bean後,馬上調用一個PostConstruct方法;或者在銷燬一個bean以前,必須調用一個PreDestroy方法。

解決方案

(1)實現InitializingBean或者DisposableBean接口,並實現的afterPropertiesSet()和destroy()方法。
(2)在<bean>元素的init-method或destroy-method屬性指定方法名稱。
(3)在PostConstruct方法方法上添加@PostConstruct註解。在PreDestroy方法上添加@PreDestroy註解。

實現InitializingBean或者DisposableBean接口

bean:
public class Cashier implements InitializingBean, DisposableBean {
... ...
  public void afterPropertiesSet() throws Exception {
    openFile();
  }
  
  public void destroy() throws Exception {
    closeFile();
  }
}


在<bean>元素的init-method或destroy-method屬性指定方法名稱

配置文件:
<bean id="cashier1" class="com.apress.springrecipes.shop.Cashier"
init-method="openFile" destroy-method="closeFile">
    <property name="name" value="cashier1" />
    <property name="path" value="c:/cashier" />
</bean>


使用註解

bean:
public class Cashier {
...
  @PostConstruct
  public void openFile() throws IOException {
    File logFile = new File(path, name + ".txt");
    writer = new BufferedWriter(new OutputStreamWriter(
    new FileOutputStream(logFile, true)));
  }

  @PreDestroy
  public void closeFile() throws IOException {
    writer.close();
  }
}

注意:
(1)@PostConstruct和@PreDestroy註解是JSR-250註解,因此須要添加JSR-250的依賴。
(2)必須在容器中註冊CommonAnnotationBeanPostProcessor實例,Spring容器才能出來這些註解。
註冊方式:
a.直接註冊實例:
<beans ...>
...
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />

<bean id="cashier1" class="com.apress.springrecipes.shop.Cashier">
<property name="name" value="cashier1" />
<property name="path" value="c:/cashier" />
</bean>
</beans>

b.添加<context:annotation-config />配置:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:annotation-config />
...
</beans>
相關文章
相關標籤/搜索