Spring中实现观察者模式

实现步骤

  1. 自定义需要发布的事件类,需要继承 ApplicationEvent

  2. 使用 @EventListener 来监听事件或者实现 ApplicationListener 接口。

  3. 使用 ApplicationEventPublisher 来发布自定义事件(@Autowired注入即可)

代码

// 事件的载体,可以定义自定义变量或者直接用 source
public class DelayTestExecuteEvent extends ApplicationEvent {
    private String domainId; // 可以增加自定义的字段

    public DelayTestExecuteEvent(Object source) {
        super(source);
    }

    public DelayTestExecuteEvent(String domainId) {
        super("");
        this.domainId = domainId;
    }

    get...

    set...
}

// 观察者
@Component
public class ExecuteObserver implements ApplicationListener<DelayTestExecuteEvent> {
    @Override
    public void onApplicationEvent(DelayTestExecuteEvent myEvent) {
        System.out.println("MyListenerA param: " + myEvent.getDomainId);
    }
}


@Controller
public class MyPublisher {

   @Autowired
   private ApplicationEventPublisher publisher;
  
   public void method() {
      // 消息发送者
      publisher.publishEvent(new DelayTestExecuteEvent("domainId"));
   }
}
posted @ 2021-05-24 18:04  LiuChengloong  阅读(139)  评论(0编辑  收藏  举报