【springboot高级】(二:自定义系统监听器,实现ApplicationListener接口。(使用篇))

    技术2022-07-12  96

    springboot在系统启动的时候,提供了很多的监听,有时候我们需要根据一些业务,在启动的时候监听springboot启动的某个节点,然后做相应的事情,那么这节就来讲一下如何实现自定义监听器,在springboot发送事件的时候,我们能够监听到。 (注意:自定义监听器和自定义初始化器原理一波一样,方式也是一模一样,如果需要看自定义初始化器的,可以查看【springboot高级】(一:自定义容器初始化器的三种方式,实现ApplicationContextInitializer接口。(使用篇)))

    首先我们需要实现org.springframework.context.ApplicationListener接口,并且指定需要监听的事件泛型,和@Order注解(执行顺序): springboot提供的事件有很多种,具体请查看官网。

    package com.osy.listener; import org.springframework.boot.context.event.ApplicationStartingEvent; import org.springframework.context.ApplicationListener; import org.springframework.core.annotation.Order; @Order(1) public class ZyOneListener implements ApplicationListener<ApplicationStartingEvent> { @Override public void onApplicationEvent(ApplicationStartingEvent event) { System.out.println(event.toString()); } }

    注册方式有三:

    方式一:让SpringFactoriesLoader进行加载,配置spring.factories

    在resources下创建文件夹META-INF,然后创建spring.factories文件 在spring.factories文件中配置ApplicationListener:(自己ZyOneListener的全限定类名)

    org.springframework.context.ApplicationListener=com.osy.listener.ZyOneListener

    方式二:向SpringApplication对象中添加Initializers

    @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication springApplication = new SpringApplication(Application.class); springApplication.addListeners(new ZyOneListener()); springApplication.run(args); } }

    方式三:在配置文件中配置,这种方式优先级order为0,跟@Order注解无关

    context.listener.classes=com.osy.listener.ZyOneListener context: listener: classes: com.osy.listener.ZyOneListener
    Processed: 0.012, SQL: 10