定义一个事件
就是一个普通的类,继承 ApplicationEvent
即可。
public class LightEvent extends ApplicationEvent {
private static final long serialVersionUID = 1L;
private LightColorEnum lightColor;
public LightEvent(Object source) {
super(source);
}
public LightEvent(Object source, LightColorEnum lightColor) {
super(source);
this.setLightColor(lightColor);
}
public LightColorEnum getLightColor() {
return lightColor;
}
public void setLightColor(LightColorEnum lightColor) {
this.lightColor = lightColor;
}
public enum LightColorEnum {
RED("stop"), YELLOW("wait"), GREEN("go");
private String message;
private LightColorEnum(String message){
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
}
监听一个事件
@Component
public class LightEventAnnotationListener {
private static final Logger log = LoggerFactory.getLogger(LightEventAnnotationListener.class);
@EventListener
@Async //异步方法
public void handler(LightEvent event){
try {
Thread.sleep(2000); //模拟一个比较耗时的操作
} catch (Exception e) {
e.printStackTrace();
}
log.info("traffic light:" + event.getLightColor().getMessage());
log.info(Thread.currentThread().getName());
}
}
发布一个事件
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
@RequestMapping("/publish")
public Object publish(){
LightEvent lightEvent = new LightEvent(this, LightEvent.LightColorEnum.YELLOW);
applicationEventPublisher.publishEvent(lightEvent);
log.info("things after publish");
return "ok";
}
异步执行
默认是同步,发布事件后,主线程会等待所有监听方法执行完毕,才会继续下一步,例如
开启异步
1、启动类
2、监听方法
监听器执行顺序
通过 SmartApplicationListener 设置优先级等,可以进行更详细的控制。
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.stereotype.Component;
/**
* 监听器
* SmartApplicationListener可以设置顺序等
*/
@Component
public class WechatListener implements SmartApplicationListener {
//设置监听优先级,越小越靠前
@Override
public int getOrder() {
return 1;
}
//监听器智能所在之一,能够根据事件类型动态监听
@Override
public boolean supportsEventType(Class<? extends ApplicationEvent> aClass) {
return aClass == OrderCreateEvent.class;
}
//监听器智能所在之二,能够根据事件发布者类型动态监听
@Override
public boolean supportsSourceType(Class<?> aClass) {
return aClass == OrderServiceImpl.class;
}
@Override
@Async
public void onApplicationEvent(ApplicationEvent applicationEvent) {
OrderCreateEvent event = (OrderCreateEvent) applicationEvent;
//发送微信
System.out.println(event.getContentList().get(0) + ",您的订单:" + event.getContentList().get(1) + "创建成功! ----by wechat");
}
}