基于Spring的事件发布与监听

public class Event extends ApplicationEvent {

    private Task task;

    /**
     * Create a new ApplicationEvent.
     *
     * @param source the object on which the event initially occurred (never {@code null})
     */
    public Event(Object source, Task task) {
        super(source);
        this.task = task;
    }
    public Task getTask() {
        return task;
    }
}
@RestController
@RequestMapping("/event")
public class EventController {
    @Autowired
    private ApplicationContext application;

    @RequestMapping("/get")
    public String get() {
        Task task = new Task();
        task.setId(1);
        task.setName("cq");
        // 发布监听事件
        application.publishEvent(new Event(this, task));
        return "ok";

    }
}
/**
 * 监听服务
 */
@Component
public class Listener implements ApplicationListener<Event> {
    @Override
    public void onApplicationEvent(Event event) {
        Task task = event.getTask();
        System.out.println("监听到消息:" + task);
    }
}
@Data
public class Task {
    private Integer id;
    private String name;
}
最后修改:2020 年 10 月 09 日 05 : 18 PM