當把一個事件發佈到Spring提供的ApplicationContext
中,被監聽器偵測到,就會執行對應的處理方法。java
事件是一個自定義的類,須要繼承Spring提供的ApplicationEvent
。app
@Data
public class MyEvent extends ApplicationEvent {
private String msg;
public MyEvent(Object source, String msg) {
super(source);
this.msg = msg;
}
}
複製代碼
基本方法是實現ApplicationListener
接口,自定義一個監聽器,實現onApplicationEvent()
方法,而後添加到ApplicationContext
。 好比:異步
public class MyListener implements ApplicationListener<MyEvent> {
@Override
public void onApplicationEvent(MyEvent event) {
System.out.print("監聽到MyEvent事件");
}
}
...
// SpringBoot的啓動類中添加監聽器
public static void main(String[] args) {
SpringApplication application = new SpringApplication(MyApplication.class);
application.addListeners(new MyListener());
application.run(args);
}
複製代碼
也能夠使用註解@EventListener
(推薦):原理就是經過掃描這個註解,建立監聽器並添加到ApplicationContext
。ide
@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();
}
}
}
複製代碼
能夠經過上下文對象的發佈方法ConfigurableApplicationContext::publishEvent()
來發布。 也能夠實現ApplicationEventPublisherAware
接口來發布(推薦)。測試
@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";
}
}
複製代碼
@SpringBootTest
@RunWith(SpringRunner.class)
public class EventServiceTest {
@Autowired
private EventService service;
@Test
public void eventTest() {
String msg="Java Code";
service.doEventWork(msg);
}
}
複製代碼
若是2個事件之間是繼承關係,會先監聽到子類事件,處理完再監聽父類。this
// 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();
}
}
}
複製代碼
默認是同步事件,如要使用異步,須要開啓異步,並使用@Async
spa