022 使用@Bean的屬性完成初始化和銷毀的指定
阿新 • • 發佈:2018-05-27
div OS pub code ostc pan per 方式 void
一 .概述
Bean的生命周期就是指,Bean的創建,初始化,銷毀的整個過程.
spring幫助我們實現整個過程,但是提供了很多的回調接口,我們
可以自己定義這些方法.
一共有四種方式可以實現這些.
二 . 使用 init-method 來實現.
組件:
public class Person {
public Person() {
System.out.println("構造器在創建對象");
}
public void init() {
System.out.println("我是init方法");
}
public void destroy() {
System.out.println("我是銷毀方法");
}
}
配置類:
@Configuration
public class LifeConfig {
@Bean(initMethod="init",destroyMethod="destroy")
public Person person() {
return new Person();
}
}
我們使用@Bean註解的使用完成指定初始化和銷毀方法.
測試類:
public class LifeTest {
private static AnnotationConfigApplicationContext context = null;
@Before
public void init() {
context = new AnnotationConfigApplicationContext(LifeConfig.class);
}
@Test
public void test1() {
}
@After
public void close() {
context .close();
}
}
這種方式很不錯.沒有什麽侵入性.
三 .實現接口完成
[1]初始化 實現InitializingBean接口
[2]銷毀實現 DisposableBean接口
這裏不做演示,因為侵入性的方式我們不喜歡用的.
四 .使用JSR-250的方式
我們也不喜歡去使用,最起碼導入這個包就已經夠煩人了.
@PostConstroct 註解 @PostConstruct 註解完成
我們也在這裏說一下就可以了.
022 使用@Bean的屬性完成初始化和銷毀的指定