spring发布订阅-EventListener

可以和业务逻辑解耦,并且支持一次发布,多次订阅(可以在多个地方接收到该事件的数据)
两种方式:
1、实现ApplicationListener接口
2、使用@EventListener

下面是基于注解来实现该demo

实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class EventDTO {
    String name;
    Integer id;
}

controller

    @GetMapping("/test/hh")
    public String show(@RequestParam Integer id, @RequestParam String name) {
        EventDTO eventDTO = new EventDTO();
        eventDTO.setId(id);
        eventDTO.setName(name);
        // 发布事件
        applicationContext.publishEvent(eventDTO);
        // 发布事件
        applicationContext.publishEvent(new EventDTO("ccc", 1222));
        return "ok";
    }

监听事件

@Component
public class TestMethodGetEvent {
    @EventListener(value = {EventDTO.class})
    public void listener11(EventDTO eventDTO) {
        System.out.println("source11 = " + eventDTO);
        // int d = 10 /0;
    }
}

这种监听的方法如果有异常抛出是影响到发布事件的方法的。比如说监听器int d = 10 /0时,在调用/test/hh接口时 会报错。

使用注解的另一种形式

    @GetMapping("/test/hh")
    public String show(@RequestParam Integer id, @RequestParam String name) {
        EventDTO eventDTO = new EventDTO();
        eventDTO.setId(id);
        eventDTO.setName(name);
        applicationContext.publishEvent(new TestGetApplicationEvent(eventDTO));
        applicationContext.publishEvent(new TestGetApplicationEvent(new EventDTO("ccc", 1222)));
        return "ok";
    }
public class TestGetApplicationEvent  extends ApplicationEvent{
    public TestGetApplicationEvent(EventDTO source) {
        super(source);
    }
}
@Component
public class TestMethodGetEvent {
    @EventListener
    public void listener(TestGetApplicationEvent applicationEvent) {
        EventDTO source = (EventDTO) applicationEvent.getSource();
        System.out.println("source = " + source);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值