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,是会抛出IllegalArgumentException
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
的一个整数值,值越小,则这个类的会越先启动,且越后停止