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");
    }
}

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

你可能感兴趣的:(spring)