场景

有些时候服务在项目启动的时候 需要记录一些日志信息、或一些其他额外操作, 那么这就需要捕捉到项目启动事件, 来完成一些扩展

实现

1. 项目启动事件

可以依赖ApplicationReadyEvent事件, 下面是测试代码
@Slf4j
@Component
public class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> {

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        try {
            String hostAddress = InetAddress.getLocalHost().getHostAddress();
            log.info("ApplicationReadyEvent事件捕捉(应用已准备好) IP:{}", hostAddress );
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

2. 项目关闭事件捕捉

可以依赖DisposableBean, 将自身注册为bean,自身被销毁的时候 会调用destroy方法
@Component
@Slf4j
public class ApplicationClosedEventListener implements DisposableBean, InitializingBean {
    @Override
    public void destroy() throws Exception {
        log.info("项目关闭事件");
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("ApplicationClosedEventListener bean被初始化之后");
    }
}

涉及到的技术点

1. 事件分类

  • spring自身的事件

  • 自定义事件
这种可以通过继承ApplicationEvent实现, eg:
@Getter
public class SleepEvent extends ApplicationEvent {

    private String user;

    /**
     * Create a new {@code ApplicationEvent}.
     *
     * @param source the object on which the event initially occurred or with
     *               which the event is associated (never {@code null})
     */
    public SleepEvent(Object source) {
        super(source);
    }

    public SleepEvent(Object source, String user) {
        super(source);
        this.user = user;
    }
}

2. springboot项目实现监听

有两种方式,这两种方式都需把监听器交给容器管理 @Component

  • 通过ApplicationListener接口实现:

    @Component
    @Slf4j
    public class SleepInterfaceListener implements ApplicationListener<SleepEvent> {
    
        @Override
        public void onApplicationEvent(SleepEvent event) {
            log.info("{} is sleeping! ApplicationListener接口实现", event.getUser() );
        }
    }
  • 通过@EventListener注解实现, @EventListener的value属性设置成监听事件 如下:

    @Component
    @Slf4j
    public class SleepAnnoListener {
    
        @EventListener(SleepEvent.class)
        public void onEvent(SleepEvent event){
            log.info("{} is sleeping! @EventListener注解实现", event.getUser());
        }
    }
  • 事件的发布

    1. 通过ApplicationContext.publishEvent方法实现

      @GetMapping("/sleepEvent")
          @ApiOperation(value = "通过ApplicationListener接口,@EventListener注解实现SleepEvent事件", httpMethod = "GET", response = R.class)
          public R<String> implementInterface() {
      
              SpringUtils.getApplicationContext().publishEvent(new SleepEvent(this,"carsonlius"));
      
              return R.success("成功的通过通过ApplicationListener接口实现了事件的监听");
          }

最后修改:2022 年 10 月 18 日
如果觉得我的文章对你有用,请点个赞吧~