springboot 事件监听使用讲解

本文介绍了Spring中使用ApplicationEvent和ApplicationListener实现事件监听与发布的原理及应用。通过创建自定义事件DemoEvent,监听器DemoEventListener,以及发布事件的PublishWay类,展示了观察者模式在Spring中的运用。在测试中,成功触发并打印了监听到的事件消息。
摘要由CSDN通过智能技术生成

1.核心两个类 以继承 一实现

继承事件类:ApplicationEventc.class

实现监听类:ApplicationListener.class

#2.用法

public class DemoEvent extends ApplicationEvent {

    private String message;

    public DemoEvent(Demo source,String message) {
        super(source);
        this.message = message;
    }
    
    public Demo getSource() {
        return (Demo)source;
    }
    
    
    public String getMessage() {
        return message;
    }
}

@Component
public class DemoEventListener implements ApplicationListener<DemoEvent> {

    @Override
    public void onApplicationEvent(DemoEvent event) {
        System.out.println("监听到事件:---》"+event.getMessage());
    }
}

@Component
public class PublishWay implements ApplicationEventPublisherAware {


    public ApplicationEventPublisher applicationEventPublisher;


    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }
}

测试:

@SpringBootTest(classes = {TestApplication.class})
public class test {

    @Autowired
    private ApplicationContext context;
    @Autowired
    PublishWay publishWay;
    @Test
    public void testEventPublic(){
       Demo demo=new Demo();
       demo.setName("hello world");
       DemoEvent demoEvent=new DemoEvent(demo,"开始测试");
       // 发布事件:方式一
       //context.publishEvent(demoEvent);
       // 发布事件:方式二
        publishWay.applicationEventPublisher.publishEvent(demoEvent);
   }
}

扩展点

此为观察者模式,举个原生的spring security用法
感兴趣可以打开源码 研究这个四个类用法 ,在这里插入图片描述
过于简单 就不展示代码了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值