使用场景
在开发中有些重要业务需要记录日志并保存.使用spring event 事件发布日志,统一监听日志并记录.使代码松耦合
使用
maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
其实只要依赖spring-core就行了,但是我要用到mvc测试所以用了web依赖
定义日志发布类
public class LogEvent extends ApplicationEvent {
private String log;
public LogEvent(Object source, String log) {
super(source);
this.log = log;
}
public String getLog() {
return log;
}
}
定义日志监听类
@Slf4j
@Component
public class LogListener implements ApplicationListener<LogEvent> {
public static Queue<String> queue = new LinkedList<>();
@Override
public void onApplicationEvent(LogEvent logEvent) {
log.info("LogListener: {} ", logEvent.getLog());
// you can save db
queue.add(logEvent.getLog());
}
}
发布
@SpringBootApplication
@RestController
public class SpringEventApplication {
@Autowired
private ApplicationContext applicationContext;
public static void main(String[] args) {
SpringApplication.run(SpringEventApplication.class, args);
}
@GetMapping("/")
public String publishLogTest() {
applicationContext.publishEvent(new LogEvent(this, "publish Log Test It's work!"));
return LogListener.queue.poll();
}
}
监听结果
- 日志输出
2018-08-17 14:13:49.465 INFO 3596 --- [nio-8080-exec-6] com.example.spring.event.LogListener : LogListener: publish Log Test It's work!
2018-08-17 14:13:49.566 INFO 3596 --- [nio-8080-exec-7] com.example.spring.event.LogListener : LogListener: publish Log Test It's work!
-
浏览器显示
示例代码github地址
问题
- 通过log会看到事件被监听了2次,会在以后的文章中解决