Spring事件(Application Event)

Spring的事件(Application Event)为Bean与Bean之间的通信提供了支持。当一个Bean处理完一个任务时,希望另一个Bean知道并能做相应的处理,这时我们就需要让另外一个Bean监听当前所发送的事件。
Demo:
自定义事件DemoEvent.java 继承ApplicationEvent

package com.example.mavenspringmvc.event;
import org.springframework.context.ApplicationEvent;

/**
 * 定义一个事件,继承ApplicationEvent
 */
public class DemoEvent extends ApplicationEvent{

    private String eventMsg;

    public DemoEvent(Object source, String eventMsg) {
        super(source);
        this.eventMsg = eventMsg;
    }

    public String getEventMsg() {
        return eventMsg;
    }

    public void setEventMsg(String eventMsg) {
        this.eventMsg = eventMsg;
    }
}

自定义事件监听器DemoEventListener.java 实现ApplicationListener接口,并指定监听的事件类型,使用onApplicationEvent方法对消息进行接受处理

package com.example.mavenspringmvc.event;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class DemoEventListener implements ApplicationListener<DemoEvent>{

    @Override
    public void onApplicationEvent(DemoEvent demoEvent) {
        String msg = demoEvent.getEventMsg();
        System.out.println("我收到了消息:" + msg);
    }
}

事件发布类DemoEventPublisher.java

package com.example.mavenspringmvc.event;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * 事件发布类,需使用spring容器来发布事件,即ApplicationContext来发布
 */
@Component
public class DemoEventPublisher {

    @Autowired
    private ApplicationContext applicationContext;

    public void publishDemoEvent(String eventMsg){
        applicationContext.publishEvent(new DemoEvent(this,eventMsg));
    }
}

测试类TestEventService.java

package com.example.mavenspringmvc.event;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class TestEventService {

    @Autowired
    private DemoEventPublisher demoEventPublisher;

    public void publishEvent(){
        demoEventPublisher.publishDemoEvent("hello application event");
    }
}

运行结果:
这里写图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值