使用事件的模式可以对系统进行解耦,事件源发布一个事件,
事件监听器可以消费这个事件,而事件源不用关注发布的事件有哪些监听器,
这可以对系统进行解耦
public class Mains extends ApplicationEvent {
public Mains(Object name) {
super(name);
System.out.println(String.format("Hi,我是被监听的%s!",name));
}
}
@Component
public class ListenerMains {
//@Async // 开启异步就无法使用@Order(0)进行排序了
@Order(0)
@EventListener(Mains.class)
public void listener(Mains mains){
System.out.println("这是第一个监听类 "+mains.getSource());
}
//@Async
@Order(1)
@EventListener(Mains.class)
public void listener2(Mains mains){
System.out.println("这是第二个监听类 "+mains.getSource());
}
//@Async
@Order(2)
@EventListener(Mains.class)
public void listener3(Mains mains){
System.out.println("这是第三个监听类 "+mains.getSource());
}
}
public class TestController {
@Autowired
GetAccessToken getAccessToken;
@Autowired
ApplicationEventPublisher publisher;
@RequestMapping("test")
public Object get() {
publisher.publishEvent(new Mains("哈哈哈哈"));
}
}