Springboot整合spring Application event

1.事件的概念

Spring的事件(Application Event)为Bean与Bean之间的消息通信提供了支持。当一个Bean处理完一个任务之后,希望另外一个Bean知道并能做相应的处理,这时我们就需要让另外一个Bean监听当前Bean所发送的事件。
Spring的事件需要遵循如下流程:
(1)自定义事件,集成ApplicationEvent。
(2)定义事件监听器,实现ApplicationListener。
(3)使用容器发布事件。
 

2.代码示例

(1)定义事件类

package com.demo.event;

import org.springframework.context.ApplicationEvent;

import java.time.Clock;

/**
 * DemoEvent
 *
 * @Description
 */

public class DemoEvent extends ApplicationEvent {

    private static final long serialVersionUID=1L;

    private String msg;


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

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public DemoEvent(Object source, Clock clock) {
        super(source, clock);
    }
}

(2)定义事件发布类

package com.demo.publisher;

import com.demo.event.DemoEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * DemoPublisher
 *
 * @Description
 */
@Component
public class DemoPublisher {
    /**
     * 注入ApplicationContext用来发布事件
     */
    @Autowired
    ApplicationContext applicationContext;

    public void publish(String msg){
        /**
         * 使用ApplicationContext的publishEvent方法来发布
         */
        applicationContext.publishEvent(new DemoEvent(this,msg));
    }

}

(3)定义事件监听类

package com.demo.listener;

import com.demo.event.DemoEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * DemoListener
 * 实现ApplicationListener接口,并指定监听的事件类型
 * @Description
 */
@Component
public class DemoListener implements ApplicationListener {
    /**
     * 使用onApplicationEvent方法对消息进行接受处理
     * @param event
     */
    @Override
    public void onApplicationEvent(DemoEvent event) {
        String msg = event.getMsg();
        System.out.println("我(bean-demoListener)接收到了bean-demoPublisher发布的消息:"+ msg);
    }
}

(4)测试类

package com.demo;

import com.demo.publisher.DemoPublisher;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;

/**
 * DemoPublisherTest
 *
 * @Description
 */
@SpringBootTest
public class DemoPublisherTest{
    @Resource
    private DemoPublisher demoPublisher;
    @Test
    public void test(){
       
        demoPublisher.publish("hello application event");
    }

}

(5)测试结果

Springboot整合spring Application event_第1张图片

你可能感兴趣的:(springboot,springboot)