Loading... # 场景 有些时候服务在项目启动的时候 需要记录一些日志信息、或一些其他额外操作, 那么这就需要捕捉到项目启动事件, 来完成一些扩展 # 实现 ## 1. 项目启动事件 > 可以依赖ApplicationReadyEvent事件, 下面是测试代码 ```java @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(); } } } ``` ![](https://img.pelycloud.com/pelyblog/2022/06/15/04db39b7-e1b0-4990-a5e4-0f6857696642.png) ## 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自身的事件 ![](https://img.pelycloud.com/pelyblog/2022/06/15/f6b7504b-231b-4c7f-842b-8cdd4a86b6d1.png) - 自定义事件 > 这种可以通过继承ApplicationEvent实现, eg: ```java @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接口实现: ```java @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方法实现 ```java @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接口实现了事件的监听"); } ``` ![](https://img.pelycloud.com/pelyblog/2022/06/15/5a54318a-cccf-496d-b7a3-7835e8fe51f6.png) 最后修改:2022 年 10 月 18 日 © 允许规范转载 赞 如果觉得我的文章对你有用,请点个赞吧~
2 条评论
教教我 ::tieba:Y.tb9:: ::tieba:Y.tb10::