關(guān)于在spring 容器初始化 bean 和銷毀前所做的操作定義方式有三種:
第一種:通過@PostConstruct 和 @PreDestroy 方法 實(shí)現(xiàn)初始化和銷毀bean之前進(jìn)行的操作
第二種是:通過 在xml中定義init-method 和 destory-method方法
第三種是: 通過bean實(shí)現(xiàn)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>
定義PersonService類:
- 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");
- }
- }
相應(yīng)的測試類:
- 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();
-
-
- }
- }
測試結(jié)果:
init
hello spring
hello spring
cleanUp
可以看出 init 方法和 clean up方法都已經(jīng)執(zhí)行了。
context.registerShutdownHook(); 是一個(gè)鉤子方法,當(dāng)jvm關(guān)閉退出的時(shí)候會調(diào)用這個(gè)鉤子方法,在設(shè)計(jì)模式之 模板模式中 通過在抽象類中定義這樣的鉤子方法由實(shí)現(xiàn)類進(jìn)行實(shí)現(xiàn),這里的實(shí)現(xiàn)類是AbstractApplicationContext,這是spring 容器優(yōu)雅關(guān)閉的方法。
|