Spring Boot学习笔记(八)spring中如何使用监听器(Listener)监听事件,完整例子

1、监听的组成

要想顺利的创建监听器,并起作用,这个过程中需要这样几个角色:

  • 事件(event)可以封装和传递监听器中要处理的参数,如对象或字符串,并作为监听器中监听的目标。
  • 监听器(listener)具体根据事件发生的业务处理模块,这里可以接收处理事件中封装的对象或字符串。
  • 事件发布者(publisher)事件发生的触发者。

2、事件的定义

我们先定义一个时间,继承org.springframework.context.ApplicationEventApplicationEvent

import org.springframework.context.ApplicationEvent;

public class EventLearn extends ApplicationEvent {
   
    private String address;
    private String text;
    
	//source 发生事件的对象
    public EventLearn(Object source, String address, String text) {
   
        super(source);
        this.address = address;
        this.text = text;
    }

    public String getAddress() {
   
        return address;
    }

    public String getText() {
   
        return text;
    }
}

3、非注解监听器:

继承import org.springframework.context.ApplicationListener
参数使用我们自定义的事件EventLearn即可

此处是instanceof用于判断类型,即传入的参数eventLearn是否是EventLearn类型

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class ApplicationListenerLearn implements ApplicationListener<EventLearn
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值