Spring中提供一些Aware相關的接口,BeanFactoryAware、ApplicationContextAware、ResourceLoaderAware、ServletContextAware等等,其中最常用到的是ApplicationContextAware。實現ApplicationContextAware的Bean,在Bean被初始後,將會被注入 ApplicationContext的實例。ApplicationContextAware提供了publishEvent()方法,實現Observer(觀察者)設計模式的事件傳播機,提供了針對Bean的事件傳播功能。通過Application.publishEvent方法,我們可以將事件通知系統內所有的ApplicationListener。
Spring事件處理一般過程:
·定義Event類,繼承org.springframework.context.ApplicationEvent.
·編寫發布事件類Publisher,實現org.springframework.context.ApplicationContextAware接口.
·覆蓋方法setApplicationContext(ApplicationContext applicationContext)和發布方法publish(Object obj)
·定義時間監聽類EventListener,實現ApplicationListener接口,實現方法onApplicationEvent(ApplicationEvent event).
java 代碼
import org.springframework.context.ApplicationEvent;
/**
* 定義事件信息
* @author new
*
*/
public class MessageEvent extends ApplicationEvent {
private String message;
public void setMessage(String message){
this.message = message;
}
public String getMessage(){
return message;
}
public MessageEvent(Object source, String message) {
super(source);
this.message = message;
// TODO Auto-generated constructor stub
}
private static final long serialVersionUID = 1L;
}
java 代碼
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class Publisher implements ApplicationContextAware {
private ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext arg0)
throws BeansException {
// TODO Auto-generated method stub
this.context = arg0;
}
public void publish(String message){
context.publishEvent(new MessageEvent(this,message));
}
public static void main(String[] args) {
ApplicationContext ctx = new FileSystemXmlApplicationContext("src/applicationContext.xml");
Publisher pub = (Publisher) ctx.getBean("publisher");
pub.publish("Hello World!");
pub.publish("The quick brown fox jumped over the lazy dog");
}
}
java 代碼
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
public class MessageEventListener implements ApplicationListener {
@Override
public void onApplicationEvent(ApplicationEvent event) {
// TODO Auto-generated method stub
if(event instanceof MessageEvent){
MessageEvent msEvent = (MessageEvent)event;
System.out.println("Received: " + msEvent.getMessage());
}
}
}
在運行期,ApplicationContext會自動在當前的所有Bean中尋找ApplicationListener接口的實現,並將其作為事件接收對象。當Application.publishEvent方法調用時,所有的ApplicationListener接口實現都會被激發,每個ApplicationListener可根據事件的類型判斷是否是自己需要處理的事件,如上面的ActionListener只處理ActionEvent事件。