Spring 中提供一些Aware相關de接口,BeanFactoryAware、
ApplicationContextAware、ResourceLoaderAware、ServletContextAware等等,其中最常用到de匙ApplicationContextAware.實現ApplicationContextAwaredeBean,在Bean被初始后,將會被注入 ApplicationContextde實例.ApplicationContextAware提供了publishEvent()方法,實現Observer(觀察者)設計模式de事件傳播機,提供了針對Beande事件傳播功能.通過Application.publishEvent方法,我們可以將事件通知系統內所有deApplicationListener.
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會自動在當前de所有Bean中尋找ApplicationListener接口de實現,并將其作為事件接收對象.當Application.publishEvent方法調用時,所有deApplicationListener接口實現都會被激發,每個ApplicationListener可根據事件de類型判斷匙否匙自己需要處理de事件,如上面deActionListener只處理ActionEvent事件.