Spring Event 观察者模式

2023-11-13  本文已影响0人  一滴矿泉水

Spring 基于观察者模式实现了自身的事件机制,由三部分组成:

注册事件

public class PublisherEvent extends ApplicationEvent {
    /**
     * 事件 id
     */
    @Getter
    private final Long eventId;

    /**
     * @param eventId Long
     */
    public PublisherEvent(Object source, Long eventId) {
        super(source);
        this.eventId = eventId;
    }

}

事件监听

方法一:实现(ApplicationListener接口)

@Slf4j
@Component
public class ApplicationEventListener implements ApplicationListener {
    @Async
    @SneakyThrows
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        PublisherEvent one =(PublisherEvent)applicationEvent;
        log.info("监听到数据(PublisherEvent) --->{}",one.getEventId());
        log.info("监听到数据类型(PublisherEvent) --->{}",one.getSource());
    }

}

方法二:使用(@EventListener注解)

@Slf4j
@Component
public class ApplicationEventListener{
    @Async
    @SneakyThrows
    @EventListener(value = PublisherEvent.class)
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        PublisherEvent one =(PublisherEvent)applicationEvent;
        log.info("监听到数据(PublisherEvent) --->{}",one.getEventId());
        log.info("监听到数据类型(PublisherEvent) --->{}",one.getSource());
    }
}

@EventListener可以指定接收的事件类型 @EventListener(value = PublisherEvent.class)

事件发布

@RestController
@RequestMapping("/event/publisher")
public class testController {
    @Resource
    ApplicationEventPublisher applicationEventPublisher;

    @PostMapping
    public void testEventPublisher(){
        PublisherEvent dto = new PublisherEvent(this,1000L);
        applicationEventPublisher.publishEvent(dto);
    }

}

文章持续更新中、希望对各位有所帮助、有问题可留言 大家共同学习 !

上一篇下一篇

猜你喜欢

热点阅读