Spring扩展之二:ApplicationListener
1.介绍
用于监听应用程序事件的接口。
子接口:GenericApplicationListener,SmartApplicationListener。
通过ApplicationEvent类和ApplicationListener接口,可以实现ApplicationContext事件处理。
ApplicationContext事件机制是观察者设计模式的实现。
@FunctionalInterface public interface ApplicationListener<E extends ApplicationEvent> extends EventListener { /** * 处理应用程序事件 */ void onApplicationEvent(E event); }
Spring内置事件:
ContextRefreshedEvent:ApplicationContext 被初始化或刷新时,该事件被发布。
@SuppressWarnings("serial") public class ContextRefreshedEvent extends ApplicationContextEvent { /** * 创建一个新的ContextRefreshedEvent事件。 * 此时source已初始化或刷新 */ public ContextRefreshedEvent(ApplicationContext source) { super(source); } }
ContextStartedEvent:ApplicationContext启动时发布的广播事件。
ContextStoppedEvent:ApplicationContext停止时发布的广播事件。
ContextClosedEvent:ApplicationContext关闭时发布的广播事件。
SpringBoot内置事件:
ApplicationStartingEvent:系统运行开始时发布的广播事件,在进行任何处理之前发布广播。
@SuppressWarnings("serial") public class ApplicationStartingEvent extends SpringApplicationEvent { /** * 创建一个新的ApplicationStartingEvent事件 * @param application 当前应用 * @param args 当前参数 */ public ApplicationStartingEvent(SpringApplication application, String[] args) { super(application, args); } }
ApplicationEnvironmentPreparedEvent:在系统环境准备完成,创建上下文之前发布的广播事件。
ApplicationContextInitializedEvent:在完成所有初始化工作之后,加载任何Bean之前发布的广播事件。
ApplicationPreparedEvent:在加载bean definitions之后,容器刷新之前发布的广播事件。
ApplicationStartedEvent:在容器刷新之后,调用任何应用程序和命令程序之前发布的广播事件。
ApplicationReadyEvent:在调用任何应用程序和命令程序之后发布的广播事件。
ApplicationFailedEvent:在启动发生异常时发布的广播事件。
2.使用
自定义事件
@SuppressWarnings("serial") public class CustomApplicationStartedEvent extends ApplicationContextEvent { // 自定义参数 private final String msg; public CustomApplicationStartedEvent(ApplicationContext source,String msg) { super(source); this.msg = msg; } //getter方法 public String getMsg() { return msg; } }
自定义监听
@Component public class CustomApplicationListener implements ApplicationListener<CustomApplicationStartedEvent> { @Override public void onApplicationEvent(CustomApplicationStartedEvent event) { System.out.println(event.getMsg()); ApplicationContext applicationContext = event.getApplicationContext(); // 打印容器里面有多少个bean System.out.println("bean count=====" + applicationContext.getBeanDefinitionCount()); // 打印所有beanName System.out.println(applicationContext.getBeanDefinitionCount() + "个Bean的名字如下:"); String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); for (String beanName : beanDefinitionNames) { System.out.println("--------"+beanName); } } }
发布广播事件
@SpringBootApplication public class SsoApplication { public static void main(String[] args) { SpringApplication application = new SpringApplication(SsoApplication .class); ConfigurableApplicationContext run = application.run(args); run.publishEvent(new CustomApplicationStartedEvent(run,"自定义监听事件")); } }