Spring 发布订阅
Spring 中的事件机制涉及到者几个类文件 :ApplicationEvent(事件类型)、ApplicationListener(事件监听类)、ApplicationEventPublisher(事件发布类)。
- ApplicationEvent:继承JDK java.util.EventObject。
public abstract class ApplicationEvent extends EventObject {
private static final long serialVersionUID = 7099057708183571937L;
private final long timestamp;
public ApplicationEvent(Object source) {
super(source);
this.timestamp = System.currentTimeMillis();
}
public final long getTimestamp() {
return this.timestamp;
}
}
- ApplicationListener :接口继承了JDK java.util.EventListener接口,泛型参数 E 必须继承 ApplicationEvent类。
@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
/**
* Handle an application event.
* @param event the event to respond to
*/
void onApplicationEvent(E event);
}
- ApplicationEventPublisher: 事件发布接口 ,实现类很多,其中子类 ApplicationContext,发布事件就用 ApplicationContext 类去发布。
TestEvent event = new TestEvent("Test event!!!");
applicationContext.publishEvent(event);
示例
1. 定义事件
public class TestEvent extends ApplicationEvent {
public TestEvent(Object source) {
// 强制调用
super(source);
}
@Override
public Object getSource() {
return super.getSource();
}
}
2. 定义事件监听者
2.1 普通类写法
@Component
public class TestEventListener1 {
@Async // 异步
@EventListener(TestEvent.class)
public void reduceStock(TestEvent testEvent) {
System.out.println("Listener message:" + testEvent.getSource());
}
}
2.2 实现ApplicationListener接口写法
@Component
public class TestEventListener implements ApplicationListener<TestEvent> {
@Override
@Async // 异步
public void onApplicationEvent(TestEvent event) {
System.out.println("Listener message:" + event.getSource());
}
}
3. 发布事件
TestEvent event = new TestEvent("Test event!!!");
applicationContext.publishEvent(event);