直接上代码:
一.定义事件
public class MyEvent extends ApplicationEvent {
private String msg;
public MyEvent(Object source, String msg) {
super(source);
this.msg = msg;
}
public String getMsg() { return msg; }
}
PS:继承ApplicationEvent
二.定义监听者
@Component
public class MyListener implements ApplicationListener<MyEvent> {
@Override
public void onApplicationEvent(MyEvent myEvent) {
//监听后的逻辑,这里简单打印
String msg = myEvent.getMsg();
System.out.println("MyListener接收到了MyPublisher发布的消息:" + msg);
}
}
PS:实现ApplicationListener接口,指定事件类型
三.定义发布者
@Component
public class MyPublisher {
@Autowired
ApplicationContext context;
public void published() {
MyEvent event = new MyEvent(this, "发布成功!");
System.out.println("发布event:" + event);
context.publishEvent(event);
}
}
PS:注入ApplicationContext ,通过ApplicationContext的publisEvent方法发布事件;
四.发布测试
@SpringBootApplication
@RestController
public class SpringDefineConfigApplication {
@Autowired
MyPublisher myPublisher;
public static void main(String[] args) {
ApplicationContext applicationContext =
SpringApplication.run(SpringDefineConfigApplication.class, args);
}
@GetMapping("/publish")
public void publish(){
myPublisher.published();
}
}
PS:注入事件发布者,只掉调用方法即可发布事件
访问/publish接口即可看到打印如下:
发布event:com.intellif.mozping.event.MyEvent[source=com.intellif.mozping.publisher.MyPublisher@690ac497]
MyListener接收到了MyPublisher发布的消息:发布成功!
上述只是简单的入门示例,可以自行完善满足特定需求。