spring 进行订阅发布时,需要几个要素
- 事件类型 : 继承ApplicationEvent
- 事件信息 : 需要传递的参数对象
- 发布信息 : 发布事件
- 处理信息 : 处理事件
下面进行详细说明:
事件类型:必须继承ApplicationEvent类,实现构造器
import org.springframework.context.ApplicationEvent;
/**
* 定义事件类型,必须继承ApplicationEvent
*/
public class QuoteEvent extends ApplicationEvent{
public QuoteEvent(Object source) {
super(source);
}
}
事件信息:事件发生时 需要发送的消息,普通bean
public class QuoteSource {
private Quote quote;
public Quote getQuote() {
return quote;
}
public void setQuote(Quote quote) {
this.quote = quote;
}
@Override
public String toString() {
return "QuoteSource{" +
"quote=" + quote +
'}';
}
}
事件发送:可以简单的使用 ApplicationContext 进行
SpringContextHolder.getApplicationContext().publishEvent(new QuoteEvent(quoteSource));
SpringContextHolder 为工具类,保存了ApplicationContext,方便获取,代码如下:
需要把此类注入spring容器中
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
public SpringContextHolder() {
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
checkApplicationContext();
return applicationContext;
}
public static <T> T getBean(String name) {
checkApplicationContext();
return applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> requiredType) {
checkApplicationContext();
return applicationContext.getBean(requiredType);
}
public static <T> Map<String, T> getBeans(Class<T> requiredType) {
return applicationContext.getBeansOfType(requiredType);
}
public static void cleanApplicationContext() {
applicationContext = null;
}
private static void checkApplicationContext() {
if(applicationContext == null) {
throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
}
}
处理消息:接受 处理消息,代码比较简单 就不解释了
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
/**
*
* 事件订阅类,监听发生的事件
* Created by xuebj on 2016/3/15.
*/
public class QuoteListener implements SmartApplicationListener {
/**
* 支持的事件类型
* @param eventType
* @return
*/
@Override
public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
return QuoteEvent.class.isAssignableFrom(eventType);
}
/**
* 支持的对象类型
* @param sourceType
* @return
*/
@Override
public boolean supportsSourceType(Class<?> sourceType) {
return QuoteSource.class.isAssignableFrom(sourceType);
}
/**
* 事件发生时此方法被触发
* @param applicationEvent
*/
@Override
public void onApplicationEvent(ApplicationEvent applicationEvent) {
//获取事件的参数对象
Quote quote = (Quote) applicationEvent.getSource();
//业务处理
}
/**
* 定义执行顺序
* @return
*/
@Override
public int getOrder() {
return 0;
}
}