zoukankan      html  css  js  c++  java
  • 带你自定义实现Spring事件驱动模型

    Spring 事件驱动模型概念

    Spring 事件驱动模型就是观察者模式很经典的一个应用,我们可以通过Spring 事件驱动模型来完成代码的解耦。

    三角色

    Spring 事件驱动模型或者说观察者模式需要三个类角色来支撑完成。分表是:

    • 事件——ApplicationEvent
    • 事件监听者——ApplicationListener
    • 事件发布者——ApplicationEventPublisher,ApplicationContext

    步骤

    1. 定义一个事件: 实现一个继承自 ApplicationEvent,并且写相应的构造函数;
    2. 定义一个事件监听者:实现 ApplicationListener 接口,重写 onApplicationEvent() 方法;
    3. 使用事件发布者发布消息: 可以通过 ApplicationEventPublisherpublishEvent() 方法发布消息。

    代码示例

    // 定义一个事件,继承自ApplicationEvent并且写相应的构造函数 注意这个事件是给发布者创建出来发送事件的,
    // 所有不能加 @Component
    public class MyApplicationEvent extends ApplicationEvent {
    
        private String message;
    
        public MyApplicationEvent(Object source,String message) {
            super(source);
            this.message = message;
        }
    
        public String getMessage() {
            return message;
        }
    
    }
    
    //// 发布事件,我们依赖于spring自带的applicationContext来发布事件,applicationContext实现了ApplicationEventPublisher 接口
    @Component
    public class MyApplicationEventPublisher {
        @Autowired
        ApplicationContext applicationContext;
    
        public void publish(String message) {
            applicationContext.publishEvent(new MyApplicationEvent(this, message));
        }
    }
    
    //// 定义一个事件监听者,实现ApplicationListener接口,重写 onApplicationEvent() 方法
    //注意泛型列是监听的事件类名
    @Component
    public class MyApplicationListener implements ApplicationListener<MyApplicationEvent> {
    
    
        @Override
        public void onApplicationEvent(MyApplicationEvent myApplicationEvent) {
            System.out.println(myApplicationEvent.getMessage());
        }
    }
    
    //测试类
    @RunWith(SpringRunner.class)
    @SpringBootTest
    @Slf4j
    public class EventTest {
    
        @Autowired
        MyApplicationEventPublisher myApplicationEventPublisher;
    
        @Test
        public void test(){
            myApplicationEventPublisher.publish("hello world");
        }
        //hello world
    }
    

    参考

    Spring使用的设计模式

  • 相关阅读:
    springmvc文件上传 并读取excel文件基本写法 多文件时参数为 @RequestParam MultipartFile[] myfiles 单文件时直接传File
    谷歌浏览器 js调试方法
    jxl实现文件导入页面例子
    angularjs实现上传文件动态显示文件列表
    文件上传 多个文件上传与单个文件上传
    angularjs实现动态表格的删除与增加
    2017songyunxin
    百万数据导出
    OutProductController
    DownloadUtil
  • 原文地址:https://www.cnblogs.com/castamere/p/15795914.html
Copyright © 2011-2022 走看看