springboot事件监听机制例子

278 阅读1分钟

springboot事件监听机制

一、什么是事件监听机制?

事件监听机制,顾名思义,就是对一个事件进行监听,当有外界刺激作用于该事件时能被捕获并产生相应的响应。

如果你知道设计模式,那么你就知道他和观察者模式非常像,监听器就是在观察事件,如果发生就去做相应的事情。

二、springboot中的事件监听机制

springboot内置了一套非常便捷的事件监听机制的实现,现在我们通过一个简单的案例来了解下他如何使用。

2.1定义事件

事件的定义只需要继承ApplicationEvent即可。

public class DeviceBatchTaskEvent extends ApplicationEvent {
    public DeviceBatchTaskEvent(DeviceBatchTask deviceBatchTask) {
        super(deviceBatchTask);
    }
}

2.2 定义监听器

定义监听器有两种方式,一种是实现ApplicationListener接口,一种是使用注解@EventListener

2.2.1 使用注解@EventListener

@EventListener
@Order(1)
public void onDeviceBatchTaskEvent(DeviceBatchTaskEvent event) {
    DeviceBatchTask deviceBatchTask = (DeviceBatchTask) event.getSource();
    System.out.println();
}

2.3.2 实现ApplicationListener接口

@Component
@Slf4j
public class DeviceBatchTaskListener1 extends ApplicationListener<DeviceBatchTaskEvent> {

    @Override
    public void onApplicationEvent(DeviceBatchTaskEvent event) {
        DeviceBatchTask deviceBatchTask = (DeviceBatchTask) event.getSource();
        System.out.println();
    }
}

2.3.3 注意

1、监听器必须放入到spring容器中

2、可以使用@Order注解来定义执行顺序

2.3 发布事件

使用容器中的ApplicationEventPublisher类来进行发布。

@Autowired
private ApplicationEventPublisher applicationEventPublisher;

public Boolean addDeviceBatchTask(String productKey, String productId, Integer applyDeviceNum) {
    DeviceBatchTask deviceBatchTask = new DeviceBatchTask();
    deviceBatchTask.setApplyDeviceNum(applyDeviceNum);
    deviceBatchTask.setId(UidUtil.getUid());
    deviceBatchTask.setProductId(Long.valueOf(productId));
    deviceBatchTask.setProductKey(productKey);
    deviceBatchTask.setLastVersion(CustomConstant.LAST_VERSION);
    deviceBatchTask.setMode(DeviceAddModeEnum.AUTO.getCode());
    deviceBatchTask.setStatus(BatchTaskStatusEnum.UNCREATE.getCode());
    HermesFillUtil.fillInsert(deviceBatchTask);
    deviceBatchTaskRepository.save(deviceBatchTask);
    //在这里事件发布
    applicationEventPublisher.publishEvent(new DeviceBatchTaskEvent(deviceBatchTask));
    return true;
}

}