public class Cashier implements InitializingBean, DisposableBean { ... ... public void afterPropertiesSet() throws Exception { openFile(); } public void destroy() throws Exception { closeFile(); } }
<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>
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(); } }
注意:
<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>