標籤:
ApplicationContext具有發布事件的能力。這是因為該介面繼承了ApplicationEventPublisher介面。Spring中與事件有關的介面和類主要包括ApplicationEvent、ApplicationListener。
定義一個事件的類需要繼承ApplicationEvent或者ApplicationContextEvent抽象類別,該抽象類別中只有一個建構函式,並 且帶有一個Object類型的參數作為事件來源,並且該事件來源不能為null,因此我們需要在自己的建構函式中執行super(Object)。
public class UserEvent extends ApplicationEvent{ private String eventContent; public String getEventContent(){ return eventContent; } public void setEventContent(String eventContent){ this.eventContent = eventContent; } public UserEvent(Object source,String eventContent){ super(source); this.eventContent = eventContent; }}
針對一種事件,可能需要特定的監聽器,因此,監聽器需要實現ApplicationListener介面。當監聽器接收到一個事件的時候,就會執行它的 onApplicationEvent()方法。由於Spring IoC中的事件模型是一種簡單的、粗粒度的監聽模型,當有一個事件到達時,所有的監聽器都會接收到,並且作出響應,如果希望只針對某些類型進行監聽,需要 在代碼中進行控制。
public class UserListener implements ApplicationListener{ public void onApplicationEvent(ApplicationEvent event){ if(event instanceof UserEvent){ //只對UserEvent類型進行處理 UserEvent ue = (UserEvent)event; String result = ue.getEventContent(); System.out.println("Event Content:"+result); } }}
對於發布事件,我們可以實現ApplicationContextAware或者ApplicationEventPublisherAware介面。
public class UserBiz implements ApplicationContextAware{private ApplicationContext applicationContext;public void setApplicationContext(ApplicationContext applicationContext) throws BeansException{ this.applicationContext = applicationContext; }public void service(String thing){ UserEvent event = new UserEvent(this,thing); event.setEventContent("I shoud "+thing); applicationContext.publishEvent(event);} }
或者如下:
public class UserBiz2 implements ApplicationEventPublisherAware{ private ApplicationEventPublisher applicationEventPublisher; public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } public void service(String thing) { UserEvent event = new UserEvent(this,thing); event.setEventContent("I shoud "+thing); applicationEventPublisher.publishEvent(event); }}
至此便完成了事件的發布,當ApplicationContext接收到事件後,事件的廣播是Spring內部給我們做的,不需要瞭解具體的細節。其實在 Spring讀取設定檔之後,利用反射,將所有實現ApplicationListener的Bean找出來,註冊為容器的事件監聽器。當接收到事件的 時候,Spring會逐個呼叫事件監聽器。剩下要做的就是在設定檔中配置監聽器。
<bean class="footprint.spring.ioc.event.UserListener"/>
Spring容器自身會發布一些事件,包括ContextClosedEvent、ContextRefreshedEvent、ContextStartedEvent、ContextStoppedEvent。
Spring中ApplicationContext對事件的支援