當把一個事件發佈到Spring提供的ApplicationContext中,被監聽器偵測到,就會執行對應的處理方法。
事件本身<br />事件是一個自定義的類,需要繼承Spring提供的ApplicationEvent 。
@Datapublic 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 。
@Component@Slf4jpublic 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@Slf4jpublic 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個事件之間是繼承關係,會先監聽到子類事件,處理完再監聽父類。
// MyEvent2 extends MyEvent@Component@Slf4jpublic 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(); } }}當我publish一個子類事件MyEvent2時,日誌如下:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。