在Spring中提供的Aware相關(guān)接口中,ApplicationContextAware是最常用到的。實(shí)現(xiàn)ApplicationContextAware的Bean,在Bean被初始后,將會(huì)被注入 ApplicationContext的實(shí)例。ApplicationContextAware提供了publishEvent()方法,通過Application.publishEvent方法,我們可以將事件通知系統(tǒng)內(nèi)所有的ApplicationListener。
Spring事件處理一般過程:
·定義Event類,繼承org.springframework.context.ApplicationEvent。
·覆蓋方法setApplicationContext(ApplicationContext applicationContext)和發(fā)布方法publish(Object obj)。
·編寫發(fā)布事件類Publisher,實(shí)現(xiàn)org.springframework.context.ApplicationContextAware接口。
·定義時(shí)間監(jiān)聽類EventListener,實(shí)現(xiàn)ApplicationListener接口,實(shí)現(xiàn)方法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
pub