當(dāng)把一個(gè)事件發(fā)布到Spring提供的ApplicationContext中,被監(jiān)聽(tīng)器偵測(cè)到,就會(huì)執(zhí)行對(duì)應(yīng)的處理方法。
事件本身
事件是一個(gè)自定義的類,需要繼承Spring提供的ApplicationEvent。
@Data
public class MyEvent extends ApplicationEvent {
private String msg;
public MyEvent(Object source, String msg) {
super(source);
this.msg = msg;
}
}
事件監(jiān)聽(tīng)
基本方法是實(shí)現(xiàn)ApplicationListener接口,自定義一個(gè)監(jiān)聽(tīng)器,實(shí)現(xiàn)onApplicationEvent()方法,然后添加到ApplicationContext。
比如:
public class MyListener implements ApplicationListener<MyEvent> {
@Override
public void onApplicationEvent(MyEvent event) {
System.out.print("監(jiān)聽(tīng)到MyEvent事件");
}
}
...
// SpringBoot的啟動(dòng)類中添加監(jiān)聽(tīng)器
public static void main(String[] args) {
SpringApplication application = new SpringApplication(MyApplication.class);
application.addListeners(new MyListener());
application.run(args);
}
也可以使用注解@EventListener(推薦):原理就是通過(guò)掃描這個(gè)注解,創(chuàng)建監(jiān)聽(tīng)器并添加到ApplicationContext。
@Component
@Slf4j
public class MyEventHandler {
@EventListener
public void handleEvent(MyEvent event) {
log.info("------------處理事件:{}", event.getMsg());
try {
Thread.sleep(5 * 1000L);
log.info("事件1(5s)處理完成");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
事件發(fā)布
可以通過(guò)上下文對(duì)象的發(fā)布方法ConfigurableApplicationContext::publishEvent()來(lái)發(fā)布。
也可以實(shí)現(xiàn)ApplicationEventPublisherAware接口來(lái)發(fā)布(推薦)。
@Component
@Slf4j
public class EventService implements ApplicationEventPublisherAware {
public ApplicationEventPublisher publisher;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.publisher = applicationEventPublisher;
}
public String doEventWork(String msg) {
log.info("------------publish event:" + msg);
MyEvent event = new MyEvent(this, msg);
publisher.publishEvent(event);
return "OK";
}
}
測(cè)試代碼
@SpringBootTest
@RunWith(SpringRunner.class)
public class EventServiceTest {
@Autowired
private EventService service;
@Test
public void eventTest() {
String msg="Java Code";
service.doEventWork(msg);
}
}
image
注意
如果2個(gè)事件之間是繼承關(guān)系,會(huì)先監(jiān)聽(tīng)到子類事件,處理完再監(jiān)聽(tīng)父類。
// MyEvent2 extends MyEvent
@Component
@Slf4j
public class MyEventHandler {
@EventListener
public void handleEvent(MyEvent event) {
log.info("------------處理事件:{}", event.getMsg());
try {
Thread.sleep(5 * 1000L);
log.info("事件1(5s)處理完成");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@EventListener
public void handleEvent2(MyEvent2 event) {
log.info("------------處理事件2:{}", event.getMsg());
try {
Thread.sleep(10 * 1000L);
log.info("事件2(10s)處理完成");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
當(dāng)我publish一個(gè)子類事件MyEvent2時(shí),日志如下:
image
默認(rèn)是同步事件,如要使用異步,需要開(kāi)啟異步,并使用@Async