Spring Event是Spring的事件通知机制,可以将相互耦合的代码解耦,从而方便功能的修改与添加。Spring Event是监听者模式的一个具体实现。
监听者模式包含了监听者Listener、事件Event、事件发布者EventPublish,过程就是EventPublish发布一个事件,被监听者捕获到,然后执行事件相应的方法。
Spring Event的相关API在spring-context包中。
Spring Event入门案例
第一步:创建maven工程springevent_demo并配置pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/>
</parent>
<groupId>cn.event</groupId>
<artifactId>springevent_demo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
第二步:创建OptLogDTO类,用于封装操作日志信息
@Data
public class OptLogDTO {
private String requestIp; //操作IP
private String type; //日志类型 LogType{OPT:操作类型;EX:异常类型}
private String userName; //操作人
private String description; //操作描述
}
第三步:创建事件类SysLogEvent
/**
* 定义系统日志事件
*/
public class SysLogEvent extends ApplicationEvent {
public SysLogEvent(OptLogDTO optLogDTO) {
super(optLogDTO);
}
}
第四步:创建监听器类SysLogListener
/**
* 异步监听日志事件
*/
@Component
public class SysLogListener {
@Async//异步处理
@EventListener(SysLogEvent.class)
public void saveSysLog(SysLogEvent event) {
OptLogDTO sysLog = (OptLogDTO) event.getSource();
long id = Thread.currentThread().getId();
System.out.println("监听到日志操作事件:" + sysLog + " 线程id:" + id);
//将日志信息保存到数据库...
}
}
第五步:创建Controller,用于发布事件
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private ApplicationContext applicationContext;
@GetMapping("/getUser")
public String getUser(){
//构造操作日志信息
OptLogDTO logInfo = new OptLogDTO();
logInfo.setRequestIp("127.0.0.1");
logInfo.setUserName("admin");
logInfo.setType("OPT");
logInfo.setDescription("查询用户信息");
//构造事件对象
ApplicationEvent event = new SysLogEvent(logInfo);
//发布事件
applicationContext.publishEvent(event);
long id = Thread.currentThread().getId();
System.out.println("发布事件,线程id:" + id);
return "OK";
}
}
第六步:创建启动类
@SpringBootApplication
@EnableAsync//启用异步处理
public class SpringEventApp {
public static void main(String[] args) {
SpringApplication.run(SpringEventApp.class,args);
}
}