SpringBoot 监听

SpringBoot在项目启动时,会对几个监听器进行回调,可以通过实现这些监听器接口,在项目启动时完成一些操作。
ApplicationContextInitializer、SpringApplicationRunListener、CommandLineRunner、ApplicationRunner

新建模块springboot_listener
创建4个类,并实现以上接口及接口方法,且都在类上添加@Component
在这里插入图片描述
实现的方法中都打印对应类及方法名称
如:
在这里插入图片描述
启动引导类
只打印了ApplicationRunner、CommandLineRunner。
也就是实现了ApplicationRunner、CommandLineRunner的类会在项目启动后执行run方法
在这里插入图片描述

对实现ApplicationRunner、CommandLineRunner的类,打印期run方法参数

在这里插入图片描述

在这里插入图片描述
输出为空
在这里插入图片描述

添加启动参数后,再打印
在这里插入图片描述
输出(这两个监听器接口,一般用其中一个就行)
在这里插入图片描述

启用ApplicationContextInitializer
创建spring.factories文件
在这里插入图片描述
指向自己定义的MyApplicationContextInitializer

org.springframework.context.ApplicationContextInitializer=\
  com.yy.springboot_listener.listener.MyApplicationContextInitializer

再启动
会在打印图标之后,IOC日志之前,一般用于项目还没有准备IOC容器之前去检测一些资源是否存在
在这里插入图片描述
启用SpringApplicationRunListener
在spring.factories文件下添加信息

org.springframework.boot.SpringApplicationRunListener=\
  com.yy.springboot_listener.listener.MySpringApplicationRunListener

此时启动会报错
原因 为SpringApplicationRunListener的构建方法中参数没有匹配,需要两个构建参数
在这里插入图片描述
参照接口的实现(第一个为自带的实现,第二个为前面的实现)
在这里插入图片描述

application为事件源。
在这里插入图片描述
依照此构建为MySpringApplicationRunListener添加构建,并去掉@Component

public MySpringApplicationRunListener(SpringApplication application, String[] args) {
    }

再启动
starting项目启动中,用得比较少,可用于硬件检测。
environmentp,环境对象准备中,准备加载配置信息。
加载完配置信息 ,打印图标。
上下文加载完,IOC容器初始化完毕。
在这里插入图片描述

springboot的事件可查看以下路径。
在这里插入图片描述

Guess you like

Origin blog.csdn.net/u012700515/article/details/121322565