前言: 事件监听模式是一种常用的设计模式, 在 springboot 中我们如何实现呢?
首先我们要理解事件监听中需要的几个角色
事件发布者 (即事件源)
事件监听者
事件本身
废话不多说直接上代码
定义事件本身
事件本身需要继承 ApplicationEvent
- package com.yxd;
- import java.util.List;
- import java.util.Map;
- import org.springframework.context.ApplicationEvent;
- public class DemoEvent extends ApplicationEvent{
- private String type;
- private List<Map> msg;
- public DemoEvent(Object object, String type ,List<Map> msg) {
- super(object);
- this.msg = msg;
- this.type = type;
- }
- public String getType() {
- return type;
- }
- public void setType(String type) {
- this.type = type;
- }
- public List<Map> getMsg() {
- return msg;
- }
- public void setMsg(List<Map> msg) {
- this.msg = msg;
- }
- }
如图:
定义事件源
事件源需要注入 ApplicationContext
- package com.yxd;
- import java.util.List;
- import java.util.Map;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.ApplicationContext;
- import org.springframework.stereotype.Component;
- @Component
- public class DemoPublisher {
- @Autowired
- ApplicationContext applicationContext;
- public void publish(String type , List<Map> msg) {
- applicationContext.publishEvent(new DemoEvent(this,type, msg ));
- }
- }
如图:
定义监听者
监听者需要实现 ApplicationListener
- package com.yxd;
- import java.util.List;
- import java.util.Map;
- import org.springframework.context.ApplicationListener;
- import org.springframework.stereotype.Component;
- @Component
- public class DemoListener1 implements ApplicationListener<DemoEvent> {
- @Override
- public void onApplicationEvent(DemoEvent event) {
- List<Map> msg = event.getMsg();
- String type = event.getType();
- System.out.println("listener1 接收到了 publisher 发送的消息类型 :" + type +", 消息内容:" + msg);
- }
- }
如图:
测试
- package com.yxd;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Map;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.Web.bind.annotation.RestController;
- @SpringBootApplication
- @RestController
- public class DemoApplication {
- public static void main(String[] args) {
- SpringApplication.run(DemoApplication.class, args);
- }
- @Autowired
- DemoPublisher demoPublisher;
- @RequestMapping("testListener")
- public String testListener() {
- ArrayList<Map> list = new ArrayList<>();
- HashMap<String, String> m1 = new HashMap<>();
- m1.put("1", "2");
- HashMap<String, String> m2 = new HashMap<>();
- m2.put("3", "4");
- HashMap<String, String> m3 = new HashMap<>();
- m3.put("5", "6");
- list.add(m1);
- list.add(m2);
- list.add(m3);
- demoPublisher.publish("测试消息",list);
- return "消息发布成功";
- }
- }
如图:
我们访问接口
三个监听者都得到了消息..
项目结构
来源: https://www.cnblogs.com/mysgk/p/9795484.html