众所周知,事件和监控在Spring框架中无处不在,打通了Spring框架的两条通道。事件和监控也是Spring框架必须要学习的核心知识之一。一般来说,我们很少用到应用程序事件,但我们不应该忘记它们的存在。例如,Spring框架内部使用各种事件来处理不同的任务。毫无疑问,在SpringBoot框架中,事件和监听器也得到了发扬光大。除了常用的SpringFramework事件(例如:ContextRefreshedEvent),SpringBoot在启动过程中还会发送一系列其他的应用程序事件。SpringBoot启动事件序列1.ApplicationStartingEvent该事件在SpringBoot应用程序开始运行时以及任何处理之前(监听器和初始化程序注册除外)发送。2.ApplicationEnvironmentPreparedEvent当已知在上下文中使用Spring环境(Environment)时,在创建Spring上下文(context)之前发送该事件。3.ApplicationContextInitializedEvent该事件在Spring应用上下文(ApplicationContext)就绪,应用初始化器(ApplicationContextInitializers)已经被调用,bean定义(beandefinitions)加载之前发送。4.ApplicationPreparedEvent该事件在Spring上下文(context)刷新之前和bean定义(beandefinitions)加载之后发送。5.ApplicationStartedEvent该事件在Spring上下文(context)刷新之后,application/command-linerunners被调用之前发送。6.AvailabilityChangeEvent该事件是在上一个事件之后立即发送的,状态:ReadinessState.CORRECT,表示应用程序已经激活。7.ApplicationReadyEvent此事件在任何应用程序/命令行运行程序调用后发送。8.AvailabilityChangeEvent该事件在上一个事件之后立即发送,状态:ReadinessState.ACCEPTING_TRAFFIC,表明应用程序已准备好接收请求。9.ApplicationFailedEvent当应用程序启动异常时发送该事件。上面描述的事件列表只包括绑定到SpringApplication的SpringApplicationEvents事件。除了这些事件之外,在ApplicationPreparedEvent之后和ApplicationStartedEvent之前还会发送以下事件:WebServerInitializedEvent这个Web服务器初始化事件在WebServer启动后发送,对应的还有ServletWebServerInitializedEvent(ServletWeb服务器初始化事件)、ReactiveWebServerInitializedEvent(响应式Web服务器初始化事件).ContextRefreshedEvent这个上下文刷新事件是在Spring应用上下文(ApplicationContext)刷新后发送的。自定义启动事件监听器既然我们知道了SpringBoot在启动过程中的各种事件,那么我们就可以在各个环节处理一些我们想做的事情了,只需要自定义一个监听器来监听一个事件就OK了。比如我们要接收上面第8步的请求,也就是应用启动后,我们简单的输出一个成功标志。SpringBoot的基本搭建这里就不介绍了。如果你对SpringBoot不是很熟悉,或者只是简单使用,建议你深入研究一下。推荐这个SpringBoot学习仓库。欢迎Star关注:https://github.com/javastacks/spring-boot-best-practice1,新监听器importlombok.extern.slf4j.Slf4j;importorg.springframework.boot.availability.AvailabilityChangeEvent;importorg.springframework.boot.availability.ReadinessState;importorg.springframework.context.ApplicationListener;/***来源微信公众号:Java技术栈*/@Slf4jpublicclassJavastackListenerimplementsApplicationListener
