Springのinit-methodとdestory-method
1942 ワード
スプリングについて 容器初期化beanと廃棄前に行った操作定義方式は3つあります.
第一種類:@PostConstructと@Predestroy方法によって、beanを初期化して廃棄する前に行う操作を実現します.
第二は、xmlにinit-methodと、 destory-method方法
三つ目は: Beanを通じてInitializingBeanとDispposable Beanインターフェースを実現します.
xmlにinit-methodとdestory-methodを配置する方法
spring容器を初期化してbeanと容器を廃棄する前に作った操作を定義します.
xmlベースの構成は一つの方法にすぎません.
直接にxmlに配置するファイル:(initの方法は無参構造の方法である必要があります.そうでないとプログラムがエラーとなります.)
init hello spring hello spring cleanUp
init方法もclean up方法もすでに実行されていることが分かります.
第一種類:@PostConstructと@Predestroy方法によって、beanを初期化して廃棄する前に行う操作を実現します.
第二は、xmlにinit-methodと、 destory-method方法
三つ目は: Beanを通じてInitializingBeanとDispposable Beanインターフェースを実現します.
xmlにinit-methodとdestory-methodを配置する方法
spring容器を初期化してbeanと容器を廃棄する前に作った操作を定義します.
xmlベースの構成は一つの方法にすぎません.
直接にxmlに配置するファイル:(initの方法は無参構造の方法である必要があります.そうでないとプログラムがエラーとなります.)
<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方法もすでに実行されていることが分かります.