spring 中的事件java
spring事件經過訂閱發佈 能夠解耦操做 能夠同步 能夠異步spring
步驟app
org.springframework.context.ApplicationEvent
來編寫事件public ApplicationEvent(Object source) { super(source); this.timestamp = System.currentTimeMillis(); }
source
爲事件傳遞的資源,在使用場景中 能夠是數據,也能夠是函數。 事件事例以下:異步
public class MySpringEvent extends ApplicationEvent { private boolean signal; /** * Create a new ApplicationEvent. * * @param signal 這裏我傳遞一個信號到事件監聽器中 */ public MySpringEvent(Boolean signal) { super(signal); this.signal=signal; } public void doSomething() { System.out.println("i am an event"); } public boolean isSignal() { return signal; } }
org.springframework.context.ApplicationEventPublisher
或者 其門面接口org.springframework.context.ApplicationEventPublisherAware
推薦門面接口相關實現以下:ide
public class MySpringEventPublisherAware implements ApplicationEventPublisherAware { private ApplicationEventPublisher applicationEventPublisher; private MySpringEvent mySpringEvent; public MySpringEventPublisherAware(MySpringEvent mySpringEvent) { this.mySpringEvent = mySpringEvent; } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } /** * 發送事件動做 事件的動做須要主動觸發 */ public void refreshEvent() { System.out.println(">>>>>>>>>>>>>>>>>>>"); this.applicationEventPublisher.publishEvent(mySpringEvent); } }
須要特別注意的是 該發佈器須要註冊爲spring bean 並且須要主動調用 org.springframework.context.ApplicationEventPublisher#publishEvent(ApplicationEvent event)
來觸發事件函數
org.springframework.context.ApplicationListener<E extends ApplicationEvent>
來實現事件的監聽public class MyApplicationEventListener implements ApplicationListener<MySpringEvent> { @Override public void onApplicationEvent(MySpringEvent event) { event.doSomething(); System.out.println(event.isSignal()); } }
經過泛型來限制監聽的事件類型,該監聽器一樣須要註冊爲spring bean。測試