SpringBoot-5.ApplicationListener子接口GenericApplicationListener, SmartApplicationListener

目录

前言

源码

应用

新建自定义的TestGenericApplicationListener类

发布事件

导入配置文件

启动


前言

ApplicationListener的两个扩展接口GenericApplicationListener和SmartApplicationListener,是对ApplicationListener的进一步封装。

新增的两个方法:

supportsEventType:判断事件类型(ApplicationEvent)是否是指定的。

supportsSourceType:默认为true,判断事件的来源是否是指定的类型

扩展接口在监听到事件之前进行判断,都满足条件的情况下,才能进行事件的接收,即进入onApplicationEvent方法。

实现接口如下图:

源码

案例源码地址

源码地址

应用

新建自定义的TestGenericApplicationListener类

当发布的事件类型为TestApplicationEvent,来源为TestApplication类时,才能执行onApplicationEvent。

package com.wzx.listener;

import com.wzx.event.TestApplication;
import com.wzx.event.TestApplicationEvent;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.core.ResolvableType;

/**
 * @Description: TODO
 * @author: wengzx
 * @date: 2021年04月21日 11:09
 */
public class TestGenericApplicationListener implements GenericApplicationListener {
    @Override
    public boolean supportsEventType(ResolvableType eventType) {
        Class<?> type = eventType.getRawClass();
        if (type == null) {
            System.out.println("supportsEventType返回false"+type);
            return false;
        }
        return TestApplicationEvent.class.isAssignableFrom(type);
    }

    @Override
    public boolean supportsSourceType(Class<?> sourceType) {
        System.out.println("supportsSourceType来源类型"+sourceType+":"+TestApplication.class.isAssignableFrom(sourceType));
        return TestApplication.class.isAssignableFrom(sourceType);

    }

    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof TestApplicationEvent) {
            System.out.println("TestGenericApplicationListener onApplicationEvent");
        }
    }
}

发布事件

导入配置文件

启动

可以看到当

supportsEventType和supportsSourceType都返回true时,才能执行onApplicationEvent方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿孟呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值