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

在这里插入图片描述

おすすめ

転載: blog.csdn.net/qq_40977118/article/details/120460561
おすすめ