關於在spring 容器初始化 bean 和銷毀前所做的操作定義方式有三種:
第一種:通過@PostConstruct 和 @PreDestroy 方法 實現初始化和銷毀bean之前進行的操作
第二種是:通過 在xml中定義init-method 和 destory-method方法
第三種是: 通過bean實現InitializingBean和 DisposableBean介面
下面示範通過 @PostConstruct 和 @PreDestory
1:定義相關的實作類別:
package com.myapp.core.annotation.init;import javax.annotation.PostConstruct;import javax.annotation.PreDestroy;public class PersonService { private String message;public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}@PostConstructpublic void init(){System.out.println("I'm init method using @PostConstrut...."+message);}@PreDestroypublic void dostory(){System.out.println("I'm destory method using @PreDestroy....."+message);}}
2:定義相關的設定檔:
<?xml version="1.0" encoding="UTF-8"?><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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.1.xsd"><!-- <context:component-scan base-package="com.myapp.core.jsr330"/> --><context:annotation-config /><bean id="personService" class="com.myapp.core.annotation.init.PersonService"> <property name="message" value="123"></property></bean></beans>
其中<context:annotation-config />告訴spring 容器採用註解配置:掃描註解配置;
測試類別:
package com.myapp.core.annotation.init;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class MainTest {public static void main(String[] args) {ApplicationContext context = new ClassPathXmlApplicationContext("resource/annotation.xml");PersonService personService = (PersonService)context.getBean("personService");personService.dostory();}}
測試結果:
I'm init method using @PostConstrut....123
I'm destory method using @PreDestroy.....123
其中也可以通過申明載入org.springframework.context.annotation.CommonAnnotationBeanPostProcessor
類來告訴Spring容器採用的 常用 註解配置的方式:
只需要修改設定檔為:
<?xml version="1.0" encoding="UTF-8"?><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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.1.xsd"><!-- <context:component-scan base-package="com.myapp.core.jsr330"/> --><!-- <context:annotation-config /> --><bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" /><bean id="personService" class="com.myapp.core.annotation.init.PersonService"> <property name="message" value="123"></property></bean></beans>
同樣可以得到以上測試的輸出結果。