關於在spring 容器初始化 bean 和銷燬前所做的操作定義方式有三種:
第一種:通過@PostConstruct 和 @PreDestroy 方法 實現初始化和銷燬bean之前進行的操作
第二種是:通過 在xml中定義init-method 和 destory-method方法
第三種是: 通過bean實現InitializingBean和 DisposableBean接口
在xml中配置 init-method和 destory-method方法
只是定義spring 容器在初始化bean 和容器銷燬之前的所做的操作
基於xml的配置只是一種方式:
直接上xml中配置文件:
- <bean id="personService" class="com.myapp.core.beanscope.PersonService" scope="singleton" init-method="init" destroy-method="cleanUp">
- </bean>
- package com.myapp.core.beanscope;
- public class PersonService {
- private String message;
- public String getMessage() {
- return message;
- }
- public void setMessage(String message) {
- this.message = message;
- }
- public void init(){
- System.out.println("init");
- }
- // how validate the destory method is a question
- public void cleanUp(){
- System.out.println("cleanUp");
- }
- }
相應的測試類:
- package com.myapp.core.beanscope;
- import org.springframework.context.support.AbstractApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- public class MainTest {
- public static void main(String[] args) {
- AbstractApplicationContext context =new ClassPathXmlApplicationContext("SpringBeans.xml");
- PersonService person = (PersonService)context.getBean("personService");
- person.setMessage("hello spring");
- PersonService person_new = (PersonService)context.getBean("personService");
- System.out.println(person.getMessage());
- System.out.println(person_new.getMessage());
- context.registerShutdownHook();
- }
- }
測試結果:
init
hello spring
hello spring
cleanUp
可以看出 init 方法和 clean up方法都已經執行了。
context.registerShutdownHook(); 是一個鉤子方法,當jvm關閉退出的時候會調用這個鉤子方法,在設計模式之 模板模式中 通過在抽象類中定義這樣的鉤子方法由實現類進行實現,這裏的實現類是AbstractApplicationContext,這是spring 容器優雅關閉的方法。
原作者出處:http://blog.csdn.net/topwqp/article/details/8681467