ApplicationEvent作用说明(帮助理解):
ApplicationEvent以及Listener是Spring为我们提供的一个事件监听、订阅的实现,内部实现原理是观察者设计模式,设计初衷也是为了系统业务逻辑之间的解耦,提高可扩展性以及可维护性
自定义Event事件
import lombok.Getter;
import lombok.Setter;
import org.springframework.context.ApplicationEvent;
import java.util.Map;
@Setter
@Getter
public class MyEvent extends ApplicationEvent {
private Map<String, String> map;
public MyEvent(Object source, Map<String, String> map) {
super(source);
this.map = map;
}
}
Event事件处理方式
第一种 通过EventListener处理
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class MyEventListenerDeal {
@EventListener
public void handleMyEventMap(MyEvent myEvent) {
log.info("------------handleMyEvent -----------");
// 測試 模擬真是業務的處理
myEvent.getMap().put("city", "beijing");
}
}
第二种通过事件ApplicationListerner加自定义的事件进行处理
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class MyEventListenerDeal implements ApplicationListener<MyEvent> {
@Override
public void onApplicationEvent(MyEvent myEvent) {
log.info("已经监听到开始处理!!!");
myEvent.getMap().put("city", "河南太热了!!!");
}
}
模拟业务层进行事件发布
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class MyEventTriggerService {
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
public Map<String, String> triggerMap() {
// 模拟实际项目业务
Map<String, String> map = new HashMap<>();
map.put("name", "zhangting");
map.put("city", "nanjing");
MyEvent myEvent = new MyEvent