业务中,经常会设计到事件监听的场景。例如,用户注册成功后,发送优惠券,发送短信通知的操作;用户支付成功,app消息通知,用户短信通知的操作。类似场景,我们会想到是完成某项动作,就触发一系列操作,我们可以使用事件触发的机制实现。
示例参考tomcat源码实现。事件的定义接口ApplicationEvent(应用事件)继承自java.util.EventObject定义事件;其他事件可以自定义,例如注册成功事件,支付成功事件。定义事件监听器接口ApplicationListener,监听ApplicationEvent事件,定义监听事件的具体操作,并且实现了Ordered接口,实现类还需要排序。定义事件广播接口ApplicationEventBroadcast,发布事件,在应用中,触发事件的位置发布事件。ApplicationEvent的代码如下:
/**
* 应用事件
**/
public class ApplicationEvent extends EventObject {
/**
* 定义事件需要的传参
*/
private final Object param;
public ApplicationEvent(Object source, Object param) {
super(source);
this.param = param;
}
public Object getParam() {
return param;
}
}
/**
* java自带的事件对象声明类,source为事件源
**/
public class EventObject implements java.io.Serializable {
private static final long serialVersionUID = 5516075349620653480L;
/**
* The object on which the Event initially occurred.
*/
protected transient Object source;
/**
* Constructs a prototypical Event.
*
* @param source The object on which the Event initially occurred.
* @exception IllegalArgumentException if source is null.
*/
public EventObject(Object source) {
if (source == null)
throw new IllegalArgumentException("null source");
this.source = source;
}
/**
* The object on which the Event initially occurred.
*
* @return The object on which the Event initially occurred.
*/
public Object getSource() {
return source;
}
/**
* Returns a String representation of this EventObject.
*
* @return A a String representation of this EventObject.
*/
public String toString() {
return getClass().getName() + "[source=" + source + "]";
}
}
事件监听器接口ApplicationListener代码如下:
/**
* 事件监听器
*
* @Author xiangquanchao
* @Date 2020/1/2 9:08
**/
public interface ApplicationListener extends Ordered {
/**
* 监听事件的逻辑
*
* @param applicationEvent 应用事件
*/
void onEvent(ApplicationEvent applicationEvent);
}
事件广播接口ApplicationEventBroadcast,代码如下:
/**
* 事件广播
**/
public interface ApplicationEventBroadcast {
/**
* 发布事件
*
* @param event 事件
*/
void publishEvent(ApplicationEvent event);
}
自定义了发送优惠券事件GiftCouponListener,作为用户注册成功后,发送优惠券的逻辑。定义了用户注册广播实现类UserRegistrationBroadcast,在用户注册成功的位置发布ApplicationEvent事件。
GiftCouponListener的代码如下:
/**
* 赠送优惠券的监听
**/
public class GiftCouponListener implements ApplicationListener {
@Override
public void onEvent(ApplicationEvent applicationEvent) {
Object param = applicationEvent.getParam();
// TODO
// 定义具体的实现逻辑
}
@Override
public int getOrder() {
return 0;
}
}
UserRegistrationBroadcast实现代码如下:
/**
* 用户注册广播
**/
public class UserRegistrationBroadcast implements ApplicationEventBroadcast {
private final List<ApplicationListener> listeners;
public UserRegistrationBroadcast(List<ApplicationListener> listeners) {
this.listeners = listeners;
AnnotationAwareOrderComparator.sort(listeners);
}
@Override
public void publishEvent(ApplicationEvent event) {
listeners.forEach(applicationListener -> applicationListener.onEvent(event));
}
}