SpringBoot 自定义监听器(Listener)

时间:2023-03-09 17:31:08
SpringBoot 自定义监听器(Listener)

1. 使用场景:在一些业务场景中,当容器初始化完成之后,需要处理一些操作,比如一些数据的加载、初始化缓存、特定任务的注册、开启线程或程序来干某些事情等等。

2. 使用步骤:

  A. 监听类实现ApplicationListener接口 ;

  B. 将监听类添加到SpringApplication实例(两种方式:application.properties配置、java启动配置)。

3. 支持的事件类型:

  A. ApplicationStartedEvent —— spring boot启动开始时执行的事件;

  B. ApplicationEnvironmentPreparedEvent —— spring boot 对应Enviroment已经准备完毕,但此时上下文context还没有创建;

  C. ApplicationPreparedEvent —— spring boot上下文context创建完成,但此时spring中的bean是没有完全加载完成的;

  D. ApplicationFailedEvent —— spring boot启动异常时执行事件 。

4.Spring内置的事件:

  A.  ContextRefreshedEvent —— ApplicationContext容器初始化或者刷新时触发该事件;

  B.  ContextStartedEvent —— 当使用ConfigurableApplicationContext接口的start()方法启动ApplicationContext容器时触发该事件;

  C. ContextClosedEvent —— 当使用ConfigurableApplicationContext接口的close()方法关闭ApplicationContext容器时触发该事件;

  D. ContextStopedEvent —— 当使用ConfigurableApplicationContext接口的stop()方法停止ApplicationContext容器时触发该事件。

5.举例说明:

package com.ruhuanxingyun;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.nsac.business.listener.ApplicationStartup; @SpringBootApplication
public class SpApp {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(SpApp.class);
springApplication.addListeners(new ApplicationStartup());
springApplication.run(args);
}
}
package com.nsac.ruhuanxingyun;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent; public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
ApplicationContext ac = event.getApplicationContext();
StepExecutor StepExecutor = new StepExecutor(ac.getEnvironment().getProperty("project-id"), ac.getBean("businessSingleJedisPool",redis.clients.jedis.JedisPool.class),
                                ac.getBean("redisCluster", redis.clients.jedis.JedisCluster.class));
Thread thread = new Thread(StepExecutor);
thread.start();
} }

可参考:https://blog.****.net/liaokailin/article/details/48186331