castamere

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使用的设计模式

分类:

Spring

技术点:

相关文章: