日常开发中长需要在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 ......");
}
}
}
启动程序,运行结果如下: