Observer pattern: spring event listening

Observer pattern: spring event listening

Previously, I wrote about the observer pattern in the design pattern column. Interested students can check it out.

Spring provides us with an event listening mechanism that can help us decouple code.

The monitoring mechanism consists of 3 parts:

事件: 继承ApplicationEvent类,可以自定义自己的事件消息
事件发布者: 通过ApplicationEventPublisher发布事件,分离业务,把业务传递给其他模块下游业务
事件监听者: 处理传播过来的事件


事件发布者--------事件--------->事件监听者

Realize event

/**
 * @author xuelongjiang
 * @description 自定义事件监听器
 **/
public class MyEvent extends ApplicationEvent {
    
    
    // 我们自定义的事件消息
    private String msg;

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

    public String getMsg() {
    
    
        return msg;
    }

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


event publisher

/**
 * @author xuelongjiang109
 * @description 事件发布器
 **/
@Component
public class EventDeal {
    
    

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    // 发布事件
    public void publish(String msg) {
    
    
        MyEvent myEvent = new MyEvent(this, msg);
        applicationEventPublisher.publishEvent(myEvent);
    }

}

event listener

    // 任意bean里都可以

    //方法级,可以一个bean里,处理多个不同的事件,便于统一管理
    @EventListener
    public void dealEvent(MyEvent myEvent) {
    
    
        System.out.println("监听到事件:" + myEvent.getMsg());
    }

In general, custom events are relatively simple. For the @EventListenerd annotation, spring is executed through cglib dynamic proxy call.
The important thing is that we must use the observer design pattern in our design and development to make our system more pluggable, highly cohesive, and low-coupled.

おすすめ

転載: blog.csdn.net/u013565163/article/details/128498571