要介入spring的生命周期,即在spring容器启动后和容器销毁前进行定制化操作,有以下四种方法:
1、实现Spring框架的InitializingBean
和DisposableBean
接口。
容器为前者调用afterPropertiesSet()
方法,为后者调用destroy()
方法,以允许bean
在初始化和销毁bean
时执行某些操作。
public class MyLifeCycle implements InitializingBean, DisposableBean { public void afterPropertiesSet() throws Exception { System.out.println("afterPropertiesSet 启动"); } public void destroy() throws Exception { System.out.println("DisposableBean 停止"); } }
2、bean自定义初始化方法和销毁方法
<bean id="MyLifeCycle" class="com.hzways.life.cycle.HelloLifeCycle" init-method="init3" destroy-method="destroy3"/>
3、@PostConstruct和@PreDestroy注解,该方法在初始化bean时依赖注入操作之后被执行。
public class MyLifeCycle { @PostConstruct private void init() { System.out.println("PostConstruct 启动"); } @PreDestroy private void destroy() { System.out.println("PreDestroy 停止"); } }
按spring中bean的生命周期执行时机来看,以上三种方式的执行顺序如下:
- 创建bean时
1. @PostConstruct 注解方式 (依赖注入完成后,populateBean方法)
2. InitializingBean 实现接口方式(初始化initializaBean方法中的自定义init方法之前)
3. custom init() 自定义初始化方法方式
- 销毁bean时
1. @PreDestroy 注解方式
2. DisposableBean 实现接口方式
3. custom destroy() 自定义销毁方法方式
4、实现LifeCycle 接口
public interface Lifecycle { void start(); void stop(); boolean isRunning(); }
spring通过委托给生命中周期处理器 LifecycleProcessor 去执行 LifeCycle 接口的方法
public interface LifecycleProcessor extends Lifecycle { /** * 响应Spring容器上下文 refresh */ void onRefresh(); /** * 响应Spring容器上下文 close */ void onClose(); }
说明:常规的LifeCycle
接口只是在容器上下文显式的调用start()
/stop()
方法时,才会去回调LifeCycle
的实现类的start
stop
方法逻辑。并不意味着在上下文刷新时自动启动。如下:
public static void main(String[] args) throws InterruptedException { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath*:services.xml"); applicationContext.start(); applicationContext.close(); }
如果要实现自动调用,可以实现LifeCycle的子类 SmartLifecycle。
public interface SmartLifecycle extends Lifecycle, Phased { /** * 如果该`Lifecycle`类所在的上下文在调用`refresh`时,希望能够自己自动进行回调,则返回`true`* , * false的值表明组件打算通过显式的start()调用来启动,类似于普通的Lifecycle实现。 */ boolean isAutoStartup(); void stop(Runnable callback); }
它通过autoStartUp来控制是否自动调用,如果为true则自动调用,为false则跟普通的LifeCycle一样。