我是靠谱客的博主 负责柚子,这篇文章主要介绍Spring提供的事件发布、订阅(学习笔记2020.11.28)Spring提供的事件发布、订阅(学习笔记2020.11.28),现在分享给大家,希望可以做个参考。
Spring提供的事件发布、订阅(学习笔记2020.11.28)
前言:
- ApplicationContext事件机制是观察者设计模式的实现,通过ApplicationEvent类和ApplicationListener接口,可以实现ApplicationContext事件处理;
- 如果容器中存在ApplicationListener的Bean,当ApplicationContext调用publishEvent方法时,对应的Bean会被触发。
Spring内置事件
内置事件 | 描述 |
---|---|
ContextRefreshedEvent | ApplicationContext 被初始化或刷新时,该事件被触发。这也可以在 ConfigurableApplicationContext接口中使用 refresh() 方法来发生。此处的初始化是指:所有的Bean被成功装载,后处理Bean被检测并激活,所有Singleton Bean 被预实例化,ApplicationContext容器已就绪可用 |
ContextStartedEvent | 当使用 ConfigurableApplicationContext (ApplicationContext子接口)接口中的 start() 方法启动 ApplicationContext 时,该事件被发布。你可以调查你的数据库,或者你可以在接受到这个事件后重启任何停止的应用程序。 |
ContextStoppedEvent | 当使用 ConfigurableApplicationContext 接口中的 stop() 停止 ApplicationContext 时,发布这个事件。你可以在接受到这个事件后做必要的清理的工作。 |
ContextClosedEvent | 当使用 ConfigurableApplicationContext 接口中的 close() 方法关闭 ApplicationContext 时,该事件被发布。一个已关闭的上下文到达生命周期末端;它不能被刷新或重启。 |
RequestHandledEvent | 这是一个 web-specific 事件,告诉所有 bean HTTP 请求已经被服务。只能应用于使用DispatcherServlet的Web应用。在使用Spring作为前端的MVC控制器时,当Spring处理用户请求结束后,系统会自动触发该事件。 |
同样事件可以自定义、监听也可以自定义,完全根据自己的业务逻辑来处理。
1.0 创建消费事件
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24/** * @Author: ZhiHao * @Date: 2020/11/27 23:03 * @Description: 消费事件( 继承spring提供的事件对象ApplicationEvent) * @Versions 1.0 **/ public class MyApplicationEvent extends ApplicationEvent { /** * 创建一个需要处理的事件(消费) * * @param source * @author: ZhiHao * @date: 2020/11/27 */ public MyApplicationEvent(Object source) { super(source); } public String test(){ System.out.println("成功触发!"); return "success"; } }
2.0 通过@EventListener
注解或者实现ApplicationListener<E>
监听接口来消费事件
2.1 @EventListener
注解
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16@Component //监听需要注册进框架管理 public class MyListener { /** * 使用注解, 方法参数就是自定义事件类型 * * @param MyApplicationEvent * @author: ZhiHao * @date: 2020/11/27 */ @EventListener public void consumption(MyApplicationEvent MyApplicationEvent){ System.out.println(MyApplicationEvent.getSource()); System.out.println(MyApplicationEvent.test()); } }
2.2 ApplicationListener<E>
监听接口
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16@Component //监听需要注册进框架管理, 接口泛型就是自定义事件类型 public class MyListenerTwo implements ApplicationListener<MyApplicationEvent> { /** * 接口实现方式 * * @param event * @author: ZhiHao * @date: 2020/11/27 */ @Override public void onApplicationEvent(MyApplicationEvent event) { System.out.println(MyApplicationEvent.getSource()); System.out.println(MyApplicationEvent.test()); } }
3.0 通过注入ApplicationEventPublisher
(事件发布者进行发布事件)
复制代码
1
2
3
4
5
6
7@Autowired private ApplicationEventPublisher publisher; public void test3( ){ //推送消息 publisher.publishEvent(new MyApplicationEvent("劳斯莱斯!")); }
1
最后
以上就是负责柚子最近收集整理的关于Spring提供的事件发布、订阅(学习笔记2020.11.28)Spring提供的事件发布、订阅(学习笔记2020.11.28)的全部内容,更多相关Spring提供内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复