Lifecycle callbacks
在spring容器中,我们可以通过一些注解和实现某些接口达到自定义这些bean的生命周期动作,比如在一个bean在被它的工厂设置了属性之后,执行它的afterPropertiesSet()方法,就是因为其实现了InitializingBean这个接口,下面我整理了一些bean生命周期相关的接口和注解
InitializingBean接口
实现了这个接口的bean,会在其工厂对其属性设置完之后,调用其afterPropertiesSet()方法以做一些初始化检测,比如jdbcTemplate:
public void afterPropertiesSet() {
if (this.getDataSource() == null) {
throw new IllegalArgumentException(\"Property \'dataSource\' is required\");
} else {
if (!this.isLazyInit()) {
this.getExceptionTranslator();
}
}
}
就在这里判断了DataSource是否被设置,如果没有设置DataSource,是会报错的
DisposableBean接口
实现了这个接口的bean,在spring容器需要销毁这个实例时调用,主要是用来释放这个实例所持有的资源,比如Redis连接等
public void destroy() {
if (this.usePool && this.pool != null) {
try {
this.pool.destroy();
} catch (Exception var2) {
log.warn(\"Cannot properly close Jedis pool\", var2);
}
this.pool = null;
}
}
@PostConstruct注解 和@PreDestroy注解
@PostConstruct和@PreDestroy会由CommonAnnotationBeanPostProcessor对持有这两个注解的对象进行处理,在bean初始化的时候调用被@PostConstruct注解的方法,在bean被销毁的时候调用被@PreDestroy注解的方法
public class CachingMovieLister {
@PostConstruct
public void populateMovieCache() {
// populates the movie cache upon initialization...
}
@PreDestroy
public void clearMovieCache() {
// clears the movie cache upon destruction...
}
}
启动和停止回调
Lifecycle 接口定义了一系列基本的对象自己的生命周期方法,但单纯只是定义了方法,如果需要在容器刷新时自动启动,则需要使用SmartLifecycle,实现这些接口的实例将委派给LifecycleProcessor来进行处理
public interface Lifecycle {
void start();
void stop();
boolean isRunning();
}
public interface SmartLifecycle extends Lifecycle, Phased {
boolean isAutoStartup();
void stop(Runnable callback);
}
实现了SmartLifecycle接口的实例,容器会在容器刷新时(context refresh)调用其start()方法,在容器正常停止时,会调用其stop(Runnable callback)方法,来停止。
SmartLifecycle接口还继承了Phased接口,这个接口里面只有一个方法getPhase(); 继承这个接口的类需要重写这个方法,返回一个Integer.MIN_VALUE 到 Integer.MAX_VALUE的一个整数值,值越小,则这个类的会越先启动,且越后停止
继续阅读与本文标签相同的文章
-
如何检测 Web 服务请求丢失问题
2026-05-18栏目: 教程
-
基于阿里云服务器ECS的建站过程
2026-05-18栏目: 教程
-
8分钟5个点让你彻底了解负载均衡
2026-05-18栏目: 教程
-
2019年9月16日,开发者社区奖励办法--8月评选结果正式公布
2026-05-18栏目: 教程
-
RocketMQ 主题扩分片后遇到的坑
2026-05-18栏目: 教程
