Spring监听事件的用法


Spring监听事件使用了设计模式中的观察者模式。

定义监听事件

自定义Event类,继承自ApplicationEvent。此处我定义了一个SceneChangeEvent:

import org.springframework.context.ApplicationEvent;

/**
 * @author windmyf
 */
public class SceneChangeEvent extends ApplicationEvent {

    private String sceneName;

    private String sceneDesc;

    public String getSceneName() {
        return sceneName;
    }

    public void setSceneName(String sceneName) {
        this.sceneName = sceneName;
    }

    public String getSceneDesc() {
        return sceneDesc;
    }

    public void setSceneDesc(String sceneDesc) {
        this.sceneDesc = sceneDesc;
    }

    /**
     * Create a new {@code ApplicationEvent}.
     *
     * @param source the object on which the event initially occurred or with
     *               which the event is associated (never {@code null})
     */
    public SceneChangeEvent(Object source) {
        super(source);
    }
}

定义监听器

定义一个监听器,实现ApplicationListener接口,重写onApplicationEvent()方法

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

/**
 * @author windmyf
 */
@Component
public class SceneChangeListener implements ApplicationListener<SceneChangeEvent> {
    @Override
    public void onApplicationEvent(SceneChangeEvent event) {
    	// TODO 监听逻辑处理
        System.out.println("场景发生了改变,场景为:" + event.getSceneDesc());
    }
}

Push事件类

该类实现ApplicationContextAware接口,通过setApplicationContext(ApplicationContext applicationContext)方法获取上下文,自定义事件push方法,并在逻辑中调用applicationContext.publishEvent();

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author windmyf
 */
@Component
public class EventPushService implements ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public void pushEvent(SceneChangeEvent sceneChangeEvent){
    	// TODO 其他逻辑处理
        System.out.println("发送场景改变消息:【" + sceneChangeEvent.getSceneName() + ","
            + sceneChangeEvent.getSceneDesc()+"】");
        // 转发事件
        applicationContext.publishEvent(sceneChangeEvent);
    }
}

当产生SceneChangeEvent事件的时候,会默认使用SceneChangeListener中的onApplicationEvent方法来进行监听器的处理。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

尘风-随手记

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

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

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

打赏作者

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

抵扣说明:

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

余额充值