基础知识

spring event 使用

2018-08-17  本文已影响99人  Learn_Java

使用场景

在开发中有些重要业务需要记录日志并保存.使用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地址

https://github.com/gbKidCoding/example-spring-event

问题

END

上一篇下一篇

猜你喜欢

热点阅读