spring event 使用

使用场景

在开发中有些重要业务需要记录日志并保存.使用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! 
  • 浏览器显示


    image.png

示例代码github地址

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

问题

  • 通过log会看到事件被监听了2次,会在以后的文章中解决

END

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,999评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,974评论 6 342
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,632评论 25 708
  • 了解情绪的力量就是健康的关键,特别是一再重复出现的想法或态度,往往决定了你是健康的还是生病了。 大家好!我是忆如尘...
    忆如尘xiao阅读 2,120评论 2 3
  • 人生的意义真的不懂,为什么有些人看见流浪狗猫就捡回去把病治好然后好好的养好?为什么她们对自己比较节约穿着旧衣服骑着...
    道悟生人阅读 255评论 0 0