日常開發中長需要在Bean初始化過程中加載一些資源或者是在Bean銷燬前釋放一些資源,Spring提供了多種不同的方式初始化和銷燬Bean。這裏我收集了幾個分享給進來的朋友們!
> 1. initMethod / destroyMethod
@Configuration
public class InitializeOne {
@Bean(initMethod = "init", destroyMethod = "destroy")
public HelloService hello() {
return new HelloService();
}
}
HelloService.java
public class HelloService {
public void init() {
System.out.println("this is init......");
}
public void destroy() {
System.out.println("this is destroy......");
}
}
> 2. InitializingBean (初始化)、DisposableBean (銷燬)
@Configuration
public class initializeTwo implements InitializingBean, DisposableBean{
@Override
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
System.out.println("this is InitializingBean 的 init......");
}
@Override
public void destroy() throws Exception {
// TODO Auto-generated method stub
System.out.println("this is DisposableBean 的 destory......");
}
}
> 3. @PostConstruct (初始化)、 @PreDestroy(銷燬)
注:這兩個不是spring的註解
@Configuration
public class initializeThree {
@PostConstruct
public void init() {
System.out.println("@PostConstruct 的 init......");
}
@PreDestroy
public void preDestory() {
System.out.println("@PreDestroy 的 preDestory......");
}
}
> 4. ContextStartedEvent (初始化)、ContextClosedEvent (銷燬)
說明:這種方式使用 Spring 事件機制,Spring 啓動之後調用ApplicationContext.start() 方法將會發送 ContextStartedEvent 事件,調用ApplicationContext.close()將會發送 ContextClosedEvent事件,這種方式會相對麻煩一些,如果不想用這種方式可以修改爲第5中方法。
@Configuration
public class initializeFour implements ApplicationListener{
@Override
public void onApplicationEvent(ApplicationEvent event) {
// TODO Auto-generated method stub
if(event instanceof ContextStartedEvent) {
System.out.println("this is ContextStartedEvent ......");
}else if(event instanceof ContextClosedEvent) {
System.out.println("this is ContextClosedEvent ......");
}
}
> 5. ApplicationListener<ContextRefreshedEvent>
說明:監聽 ContextRefreshedEvent 事件,一旦 Spring 容器初始化完成,就會發送 ContextRefreshedEvent。
@Configuration
public class initializeFour implements ApplicationListener<ContextRefreshedEvent>{
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
// TODO Auto-generated method stub
if(event.getApplicationContext().getParent() == null) {
System.out.println("this is ContextRefreshedEvent ......");
}
}
}
啓動程序,運行結果如下: