SpringBoot使用@EventListener实现事件监听

1. 创建监听实体类UserEvent

  • 实现ApplicationEvent类,重载构造方法加入具体的message
package com.example.fisher.gradledemo.event.entity;

import org.springframework.context.ApplicationEvent;

public class UserEvent extends ApplicationEvent {

    //需要发送的具体内容
    private String msg;

    public UserEvent(Object source, String msg) {
        super(source);
        this.msg = msg;
    }

    public String getMsg() {
        return msg;
    }
}

2. 创建监听类UserEventListener

package com.example.fisher.gradledemo.event.listener;

import com.example.fisher.gradledemo.event.entity.UserEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class UserEventListener {

    @EventListener(UserEvent.class)
    @Async
    public void userEvent(UserEvent userEvent) {
        log.info("UserEvent:{}", userEvent.getMsg());
    }

}

3. 创建controller,发送事件

package com.example.fisher.gradledemo.event.controller;

import com.example.fisher.gradledemo.event.entity.UserEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("event")
public class EventController {

    @Resource
    private ApplicationContext applicationContext;

    @GetMapping
    public void sendEvent() {
        applicationContext.publishEvent(new UserEvent(this, "fisher"));
    }

}

4. 启动类

  • 如果需要做异步监听,需要在启动类上添加异步注解@EnableAsync,监听方法上添加注解@Async
  • 调用接口http://localhost:8080/event,查看打印

2021-09-24 18:05:08.927 INFO 6025 — [ task-2] c.e.f.g.e.listener.UserEventListener : UserEvent:fisher

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值