本学习记录的代码,大部分参考自gitee码云的如下工程。这个工程有详尽的Spingboot1.x教程,并且2.x也在更新中。鸣谢!
https://gitee.com/didispace/SpringBoot-Learning.git
本学习记录的示例代码克隆地址,分支为develop
https://gitee.com/kutilion/MyArtifactForEffectiveJava.git
在使用BootApplication.java启动服务的时候,会发现控制台输出了一些自定义信息。其中有一部分是通过Spring boot的事件输出的。Springboot启动时的事件主要由以下几种:
- ApplicationStartingEvent 启动开始时
- ApplicationEnvironmentPreparedEvent 环境准备完毕时
- ApplicationPreparedEvent 所有需求全部准备完毕时
- ApplicationStartedEvent 应用程序启动完毕时
- ApplicationReadyEvent 应用程序准备完毕时
- ApplicationFailedEvent 应用程序启动失败时
出了最后的应用程序启动失败时时间,其他时间按照上述顺序执行。
相关代码:
- studySpringboot.n03.applicationevent.ApplicationStartingEventListener.java
- studySpringboot.n03.applicationevent.ApplicationEnvironmentPreparedEventListener.java
- studySpringboot.n03.applicationevent.ApplicationPreparedEventListener.java
- studySpringboot.n03.applicationevent.ApplicationStartedEventListener.java
- studySpringboot.n03.applicationevent.ApplicationReadyEventListener.java
- studySpringboot.n03.applicationevent.ApplicationFailedEventListener.java
- studySpringboot.BootApplication.java
BootApplication.java
1.将各个监听器类加载进上下文
// Application event listener test start sa.addListeners(new ApplicationStartingEventListener()); sa.addListeners(new ApplicationEnvironmentPreparedEventListener()); sa.addListeners(new ApplicationPreparedEventListener()); sa.addListeners(new ApplicationStartedEventListener()); sa.addListeners(new ApplicationReadyEventListener()); sa.addListeners(new ApplicationFailedEventListener()); // Application event listener test end
2.测试读入控制台参数的事件和服务启动事件的先后顺序所用代码
// Application event listener test start @Bean public DataLoader dataLoader() { return new DataLoader(); } static class DataLoader implements CommandLineRunner { @Override public void run(String... strings) throws Exception { System.out.println("Springboot command-line runners --------------------------"); } } // Application event listener test start
监听器代码
其他的监听器实现了ApplicationListener接口,并且重写了接口的onApplicationEvent方法,输出测试文本。比如ApplicationStartingEventListener类:
public class ApplicationStartingEventListener implements ApplicationListener { @Override public void onApplicationEvent(ApplicationStartingEvent event) { System.out.println("Springboot application starting event --------------------------"); }}
在启动后可以在控制台看到如下结果
![5c2aa5959766e03cf0047b998d956961.png](https://img-blog.csdnimg.cn/img_convert/5c2aa5959766e03cf0047b998d956961.png)
红色为各个事件的输出,蓝色的是读入控制台输入参数时触发的事件。可以看到读入控制台输入参数的事件在ApplicationStartedEvent 与ApplicationReadyEvent 之间。
应用程序启动失败时的事件没有进行测试。
总结:
- 确认服务启动时各种事件的先后顺序
- 事件的实装方法
- 读取控制台输入事件