一、概念:
二、使用要点:
事件对象通过继承ApplicationEvent类来定义。
事件监听者通过实现ApplicationListener接口来定义,并配置到spring容器中,spring容器会自动注册该事件监听器。
事件发布者可以通过实现ApplicationEventPublisher接口来定义
调用事件发布者的publishEvent方法发布了事件对象后,事件对象会传入到事件监听者的onApplicationEvent方法中。
业务类通过实现ApplicationEventPublisherAware接口,可以自动植入事件发布者对象。
三、范例:
事件发布者:
@Component
public class TellerEventPublisher implements ApplicationEventPublisher {
private ApplicationEventPublisher publisher;
@Override
public void publishEvent(ApplicationEvent event) {
publisher.publishEvent(event);
}
@Autowired
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
}
事件对象:
public class TellerLoginEvent extends ApplicationEvent {
public TellerLoginEvent(Object source) {
super(source);
}
}
事件监听器:
@Component
public class TellerLoginListener implements ApplicationListener<TellerLoginEvent> {
@Override
public void onApplicationEvent(TellerLoginEvent event) {
ITellerConnection conn = (ITellerConnection) event.getSource();
TellerLogger.log.info("uid:" + conn.getUid() + " fired login event");
......
}
}
发布事件:
public class Test{
@Autowired
private TellerEventPublisher publisher;
public void doSomething(){
TellerLoginEvent event = new TellerLoginEvent(eventSource);
publisher.publishEvent(event);
}
}