spring boot 提供的关于应用启动过程生命周期函数的简单使用

290 阅读2分钟

SpringApplicationRunListener介绍

spring boot提供的,方便用户在spring boot应用启动的不同生命阶段对应用进行控制.提供的接口 SpringApplicationRunListener

生命周期介绍

在 spring boot 2.3.4RELEASE版本中,提供了七个有默认实现的函数.分别对应了spring启动生命周期的阶段.

  • starting

    在spring主程序,即使用@SpringBootApplication注解的类使用main方法中run运行后,执行该方法中的代码.

  • environmentPrepared

    ApplicationContextspring上下文初始化之前,但其他环境已经准备之后,执行该方法中的代码.

  • contextPrepared

    ApplicationContext创建完成后,但是其他资源文件还未加载时,执行该方法中的代码.

  • contextLoaded

    ApplicationContext刷新之前,执行该方法中的代码.

  • started

    ApplicationContext已经刷新,应用已经启动,但是CommandLineRunnerApplicationRunner还没执行.执行该方法中的代码

  • running

    CommandLineRunnerApplicationRunner已经执行.执行该方法中的代码

  • failed

    启动失败的时候,执行该方法中的代码

具体使用

因为这个类需要在spring早期的时候就被spring认识,所以不可以使用诸如@componet等注解加入spring的bean管理中. 这里也使用spring提供的配置文件实现. 在path/projectName/src/main/resources下新建文件夹META-INF,并在此文件下建立文件spring.factories. 文件内容为

org.springframework.boot.SpringApplicationRunListener=com.*.*.MyRunListener

接着在项目中新建MyRunListener类,并构造一个构造函数如下.

public class MyRunListener implements SpringApplicationRunListener {

  private final SpringApplication application;
  private final String[] args;

  public MyRunListener(SpringApplication sa, String[] args) {
    this.application = sa;
    this.args = args;
  }

}

其中的参数必须为指定的这两种类型.

最后实现SpringApplicationRunListener中的我们想要实现的方法.

ps:上述的接口提供的方法有可能有变.截止2.6.0的版本,已经标记废弃了started等接口.并新增了一些接口. 实现接口函数时建议查看对应版本SpringApplicationRunListener的实际实现.