spring boot 事件
spring boot 事件
spring boot 的事件(Application Event) 为Bean与Bean之间的消息通信提供了支持。当一个Bean处理完一个任务之后,希望另外一个 Bean 知道并能做相应的处理,这时,我们需要让另外一个Bean监听当前Bean所发送的事件。
事件流程
我们对Markdown编辑器进行了一些功能拓展与语法支持,除了标准的Markdown编辑器功能,我们增加了如下几点新功能,帮助你用它写博客:
- 自定义事件,集成ApplicationEvent
- 定义事件监听器,实现ApplicationListener
- **使用容器发布事件
示例
- 自定义事件
package com.example.demo.event;
import org.springframework.context.ApplicationEvent;
/**
* 自定义事件
*/
public class DemoEvent extends ApplicationEvent {
private String msg;
public DemoEvent(Object source, String msg) {
super(source);
this.msg = msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
- 事件监听器
package com.example.demo.event;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
/**
* 定义事件监听
*/
@Component
public class DemoListener implements ApplicationListener<DemoEvent> { // 指定监听的事件类型--DemoEvent
@Override
public void onApplicationEvent(DemoEvent demoEvent) { // 接受消息并处理
String msg = demoEvent.getMsg();
System.out.println("我(bean-demoListener)接收到了bean-demoPublisher发布的消息: = " + msg);
}
}
- 事件发布类
package com.example.demo.event;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class DemoPulisher {
@Autowired
private ApplicationContext applicationContext; // 注入Application用来发布事件
public void publish(String msg) { // 发布事件
applicationContext.publishEvent(new DemoEvent(this, msg));
}
}
- 配置类
package com.example.demo.event;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.example.demo.event")
public class EventConfig {
}
- 调用
package com.example.demo.controller;
import com.example.demo.config.SpringContextUtil;
import com.example.demo.event.DemoPulisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Autowired
private DemoPulisher demoPulisher;
@GetMapping("/event")
public String event(String msg) {
demoPulisher.publish(msg);
return msg;
}
}