springBoot中,监听和处理事件是一个比较常见的任务,spring框架它提供了比较多的方式来实现这一点。比如咱们举一个简单的例子,可以看一下如何在springBoot中监听和处理事件。

1.咱们可以先定义一个事件类,继承一下ApplicationEvent

import org.springframework.context.ApplicationEvent;

public class CustomEventTest extends ApplicationEvent {

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

    public String getMessage() {
        return msg;
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

2.然后发布事件,发布事件的时候会用到一个组件,可以使用ApplicationEventPublisher来发布事件。看以下例子

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

/**
 * 发布事件
 */
@Component
public class CustomEventPublisherTest {

    //CustomEventPublisherTest@Component注解,使其成为一个Spring管理的Bean。

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    public void publishCustomEvent(final String message) {
        System.out.println("这是发布事件============");
        CustomEventTest test = new CustomEventTest(this, message);
        applicationEventPublisher.publishEvent(test);
    }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

3.最后呢就是需要一个监听器来处理这个事件,可以用@EventListener注解来监听事件。

import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * 监听事件
 */
@Component
public class EventListenerTest {
    @EventListener
    public void handleCustomEvent(CustomEventTest eventTest) {
        System.out.println("监听事件" + eventTest.getMessage());
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

4.接下来我们进行测试,在controller中调用CustomEventPublisherTest发布事件。


    @Autowired
    private CustomEventPublisherTest customEventPublisher;

    @GetMapping("/publishEvent")
    public String publishEvent(@RequestParam String message) {
        customEventPublisher.publishCustomEvent(message);
        return "Event Published";
    }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

结语:通过以上步骤,可以在springBoot中实现事件发布和监听。也可以根据需要定义多个事件监听器。