Java 监听机制
SpringBoot 的监听机制,其实是对Java提供的事件监听机制的封装。
Java中的事件监听机制定义了以下几个角色:
- 事件:Event,继承
java.util.EventObject
类的对象 - 事件源:Source ,任意对象Object
- 监听器:Listener,实现
java.util.EventListener
接口 的对象
SpringBoot 监听机制
SpringBoot 在项目启动时,会对几个监听器进行回调,我们可以实现这些监听器接口,在项目启动时完成一些操作。
ApplicationContextInitializer
、SpringApplicationRunListener
、CommandLineRunner
、ApplicationRunner
META-INF/spring.factories
org.springframework.context.ApplicationContextInitializer=com.release.springbootlistener.listener.MyApplicationContextInitializerorg.springframework.boot.SpringApplicationRunListener=com.release.springbootlistener.listener.MySpringApplicationRunListener
-
ApplicationContextInitializer
@Component public class MyApplicationContextInitializer implements ApplicationContextInitializer {@Overridepublic void initialize(ConfigurableApplicationContext applicationContext) {System.out.println("ApplicationContextInitializer....initialize");} }
-
SpringApplicationRunListener
public class MySpringApplicationRunListener implements SpringApplicationRunListener {public MySpringApplicationRunListener(SpringApplication application, String[] args) {}@Overridepublic void starting() {System.out.println("starting...项目启动中");}@Overridepublic void environmentPrepared(ConfigurableEnvironment environment) {System.out.println("environmentPrepared...环境对象开始准备");}@Overridepublic void contextPrepared(ConfigurableApplicationContext context) {System.out.println("contextPrepared...上下文对象开始准备");}@Overridepublic void contextLoaded(ConfigurableApplicationContext context) {System.out.println("contextLoaded...上下文对象开始加载");}@Overridepublic void started(ConfigurableApplicationContext context) {System.out.println("started...上下文对象加载完成");}@Overridepublic void running(ConfigurableApplicationContext context) {System.out.println("running...项目启动完成,开始运行");}@Overridepublic void failed(ConfigurableApplicationContext context, Throwable exception) {System.out.println("failed...项目启动失败");} }
-
CommandLineRunner
@Component public class MyCommandLineRunner implements CommandLineRunner {@Overridepublic void run(String... args) throws Exception {System.out.println("CommandLineRunner...run");System.out.println(Arrays.asList(args));} }
-
ApplicationRunner
/*** 当项目启动后执行run方法。*/ @Component public class MyApplicationRunner implements ApplicationRunner {@Overridepublic void run(ApplicationArguments args) throws Exception {System.out.println("ApplicationRunner...run");System.out.println(Arrays.asList(args.getSourceArgs()));} }