Spring Boot 异步事件 Event

异步事件 Event

1. 定义事件类 Event

继承 ApplicationEvent

1
2
3
4
5
6
7
8
public class OpLogEvent extends ApplicationEvent {
public OpLogEvent(OpLog log) {
super(log);
this.log = log;
}

private OpLog log;
}

2. 创建事件监听类 Listener

实现 ApplicationListener 接口

1
2
3
4
5
6
7
8
9
10
11
12
@Component
public class OpLogService implements ApplicationListener<OpLogEvent> {

@Autowired
OpLogMapper opLogMapper;

@Override
public void onApplicationEvent(OpLogEvent event) {
OpLog entity = event.getLog();
opLogMapper.insert(entity);
}
}

3. 事件发布

在需要的地方调用 ApplicationEventPublisherApplicationContext 的方法 publishEvent

1
2
OpLogEvent event = new OpLogEvent(log);
applicationContext.publishEvent(event);