springboot启动事件监听器退出钩子
1. 应用程序事件和监听器
除了通常的Spring Framework事件之外,例如 ContextRefreshedEvent,SpringApplication发送一些额外的应用程序事件。
![]()  | 
| 
 某些事件实际上是在ApplicationContext创建之前触发的,因此您无法在这些事件上注册侦听器 您可以使用 如果您希望自动注册这些侦听器,无论应用程序的创建方式如何,可以向项目添加文件META-INF/spring.factories并使用该 org.springframework.context.ApplicationListener = com.example.project.MyListener
 | 
应用程序运行时,应按以下顺序发送应用程序事件:
- 一个
ApplicationStartingEvent,是在一个运行的开始,但任何处理之前被发送,除了listeners 和initializers注册者。 - 一个
ApplicationEnvironmentPreparedEvent,Environment已知,但是在创建上下文之前。 - 一个
ApplicationPreparedEvent,是在刷新开始前,但bean定义已经被加载之后。 - 一个
ApplicationStartedEvent,上下文已被刷新后发送,但是在调用command-line runners 之前。 一个ApplicationReadyEvent,command-line runners已经被调用。它表示应用程序已准备好为请求提供服务。- 一个
ApplicationFailedEvent,如果在启动时异常发送。 
一个SpringApplication试图创建正确类型的ApplicationContext。用于确定WebApplicationType的算法非常简单:
- 如果存在Spring MVC,则使用
AnnotationConfigServletWebServerApplicationContext - 如果Spring MVC不存在且存在Spring WebFlux,则使用
AnnotationConfigReactiveWebServerApplicationContext - 否则,
AnnotationConfigApplicationContext使用 
这意味着如果您WebClient在同一个应用程序中使用Spring MVC和Spring WebFlux中的新版本,则默认情况下将使用Spring MVC。您可以通过调用setWebApplicationType(WebApplicationType)轻松覆盖它。
也可以完全控制ApplicationContext调用所使用的类型setApplicationContextClass(…)。
3.使用ApplicationRunner或CommandLineRunner
如果您需要在启动SpringApplication后运行某些特定代码,则可以实现ApplicationRunner或CommandLineRunner接口。
两个接口以相同的方式工作并提供单个run方法,该方法在SpringApplication.run(…)完成之前调用 。
所述CommandLineRunner接口提供访问的应用程序的参数作为一个简单的字符串数组,而ApplicationRunner使用了ApplicationArguments前面所讨论的接口。以下示例显示了CommandLineRunner一个run方法:
import org.springframework.boot.*; import org.springframework.stereotype.*; @Component public class MyBean implements CommandLineRunner { public void run(String... args) { // Do something... } }
如果定义了必须按特定顺序调用的多个CommandLineRunner或ApplicationRunnerbean,则可以另外实现 org.springframework.core.Ordered接口或使用org.springframework.core.annotation.Order注释。
4.应用退出
每个SpringApplication都注册一个JVM的关闭钩子,以确保 ApplicationContext在退出时正常关闭。可以使用所有标准的Spring生命周期回调(例如DisposableBean接口或@PreDestroy注释)。
此外,如果bean 在SpringApplication.exit()调用时希望返回特定的退出代码,则可以实现接口org.springframework.boot.ExitCodeGenerator 。然后可以传递此退出代码System.exit()以将其作为状态代码返回,如以下示例所示:
@SpringBootApplication public class ExitCodeApplication { @Bean public ExitCodeGenerator exitCodeGenerator() { return () -> 42; } public static void main(String[] args) { System.exit(SpringApplication .exit(SpringApplication.run(ExitCodeApplication.class, args))); } }

![[Note]](https://docs.spring.io/spring-boot/docs/2.1.3.RELEASE/reference/htmlsingle/images/note.png)
                
            
        
浙公网安备 33010602011771号