Spring中的一些自定义生命周期接口和注解

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

参考资料:
[1] https://docs.spring.io/spring/docs/4.3.21.RELEASE/spring-framework-reference/htmlsingle/#beans-factory-nature

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值