springboot监听机制,其实是对java提供的事件监听机制的封装。
Java中的事件监听机制定义了以下几个角色:
事件:Event,继承EventObject类,例如点击,拖动等等。
事件源:Source,任意对象的Object
监听器:Listener,实现EventListener接口对象,用来监听事件源上是否有事件
springboot项目启动时,会对几个监听器进行回调,我们可以实现这些监听器接口用来处理我们自己的逻辑。常见接口:
ApplicationContextlnitializer
SpringApplicationRunListener
CommandLineRunner
ApplicationRunner
CommandLineRunner 和ApplicationRunner
1、不需要额外配置,仅仅实现该接口
2、实现该接口,重写run方法。
3、项目启动后,方法执行。
ApplicationContextlnitializer
作用:项目启动时,准备一些资源。
步骤:
需要创建MATE-INF/spring.factories
配置org.springframework.context.ApplicationContextInitializer=\com.msf.listener.MyApplicationContextInitializer
结果:
SpringApplicationRunListener
作用:spring声明周期相关的监听接口;
步骤:与ApplicationContextlnitializer配置相同
结果:
简单的了解springboot的事件监听机制了,我们需要用它们做一些事情。
在debug形式下启动项目
public ConfigurableApplicationContext run(String... args) {long startTime = System.nanoTime(); // 计时DefaultBootstrapContext bootstrapContext = createBootstrapContext();ConfigurableApplicationContext context = null;configureHeadlessProperty();// !!!获取所有的listener!SpringApplicationRunListeners listeners = getRunListeners(args);listeners.starting(bootstrapContext, this.mainApplicationClass);try {ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);// 环境准备ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments);// 环境信息准备configureIgnoreBeanInfo(environment);// 打印图标Banner printedBanner = printBanner(environment);// !!!IOC容器创建!context = createApplicationContext();context.setApplicationStartup(this.applicationStartup);prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);// 刷新 contextrefreshContext(context);afterRefresh(context, applicationArguments);Duration timeTakenToStartup = Duration.ofNanos(System.nanoTime() - startTime);if (this.logStartupInfo) {new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), timeTakenToStartup);}listeners.started(context, timeTakenToStartup);callRunners(context, applicationArguments);}catch (Throwable ex) {handleRunFailure(context, ex, listeners);throw new IllegalStateException(ex);}try {Duration timeTakenToReady = Duration.ofNanos(System.nanoTime() - startTime);listeners.ready(context, timeTakenToReady);}catch (Throwable ex) {handleRunFailure(context, ex, null);throw new IllegalStateException(ex);}return context;}
重点代码:
获取所有的listener!
SpringApplicationRunListeners listeners = getRunListeners(args);
b. 环境准备
ConfigurableEnvironment environment = prepareEnvironment
c. 创建IoC容器
context = createApplicationContext();
d. 刷新IoC容器
refreshContext(context);
整个流程如下图所示