文章目录
参考资料
运行环境
- windows10
- JDK 8
- IDEA 专业版
- SpringBoot 2.5.6
一、SpringBoot 监听机制
SpringBoot的监听机制,其实是对Java提供的事件监听机制的封装
Java中的事件监听机制定义了以下几个角色:
- 事件:
Event
,继承java.util.EventObject
类的对象 - 事件源:
Source
,任意对象Object
- 监听器:
Listener
,实现java.util.EventListener
接口的对象
在 SpringBoot项目启动时,会对几个监听器进行回调,我们可以实现这些监听器接口,在项目启动时完成一些操作
- ApplicationContextInitializer
- SpringApplicationRunListener
- CommandLineRunner
- ApplicationRunner
测试的项目结构:
spring.factories
用于指定springboot容器的监听类
org.springframework.context.ApplicationContextInitializer=com.uni.listener.MyApplicationContextInitializer
org.springframework.boot.SpringApplicationRunListener=com.uni.listener.MySpringApplicationRunListener
MyApplicationContextInitializer.java
package com.uni.listener;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class MyApplicationContextInitializer implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
System.out.println("ApplicationContextInitializer....initialize");
}
}
MyApplicationRunner.java
package com.uni.listener;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner...run");
System.out.println(Arrays.asList(args.getSourceArgs()));
}
}
MyCommandLineRunner.java
package com.uni.listener;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner...run");
System.out.println(Arrays.asList(args));
}
}
MySpringApplicationRunListener.java
package com.uni.listener;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.stereotype.Component;
import java.time.Duration;
public class MySpringApplicationRunListener implements SpringApplicationRunListener {
public MySpringApplicationRunListener(SpringApplication application, String[] args) {
}
@Override
public void starting(ConfigurableBootstrapContext bootstrapContext) {
System.out.println("starting...项目启动中");
}
@Override
public