spring的init-method 和 destory-method
阿新 • • 發佈:2019-02-02
關於在spring 容器初始化 bean 和銷燬前所做的操作定義方式有三種:
在xml中配置 init-method和 destory-method方法
只是定義spring 容器在初始化bean 和容器銷燬之前的所做的操作
基於xml的配置只是一種方式:
直接上xml中配置檔案:
- <beanid="personService"class="com.myapp.core.beanscope.PersonService"scope="singleton"init-method="init"destroy-method="cleanUp">
-
</bean
- package com.myapp.core.beanscope;
- publicclass PersonService {
- private String message;
- public String getMessage() {
- return message;
- }
- publicvoid setMessage(String message) {
- this.message = message;
- }
-
publicvoid init(){
- System.out.println("init");
- }
- // how validate the destory method is a question
- publicvoid cleanUp(){
- System.out.println("cleanUp");
- }
- }
相應的測試類:
- package com.myapp.core.beanscope;
-
import org.springframework.context.support.AbstractApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- publicclass MainTest {
- publicstaticvoid 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 容器優雅關閉的方法