观察者模式的机制:
ApplicationContext发布ApplicationEvent时,ApplicationListener就会自动触发
实现观察者模式的三个必要条件:
①:自定义事件(event)继承 ApplicationEvent(也有Spring 自己提供的事件)
// 事件
public class MyApplicationEvent extends ApplicationEvent {
public MyApplicationEvent(Object source) {
super(source);
}
}
②:监听器(listener)实现 ApplicationListener(对自己定义事件进行监听)
public class MyApplicationListener implements ApplicationListener<MyApplicationEvent> {
@Override
public void onApplicationEvent(MyApplicationEvent myApplicationEvent) {
System.out.println("lister start!!!!!!!");
}
}
③:ApplicationContext添加监听器(此处可以依赖注入)
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = SpringApplication.run(CloudBiz1Application.class, args);
applicationContext.addApplicationListener(new MyApplicationListener());
}
再回到观察者模式机制:
ApplicationContext发布ApplicationEvent时,ApplicationListener就会自动触发
@RequestMapping("pl")
public String haha(@RequestBody @Validated ApiInDto apiIn, BindingResult result) throws Exception {
hasError(result);
CompletableFuture<List<String>> listCompletableFuture = CompletableFuture
.supplyAsync(() -> publicService.add());
CompletableFuture<List<String>> listCompletableFuture1 = CompletableFuture.supplyAsync(()
-> domoService.mins()
);
//发布事件
applicationContext.publishEvent(new MyApplicationEvent("sucessfully"));
return "HAHA";
}
postman发送请求后,此时控制台↓
(当监听器观察到ApplicationContext发布事件时,监听器里的逻辑就自动触发了)
?lister start!!!!!!!
|