观察者模式之spring事件机制

ddsspring中的事件机制使用到设计模式中的观察者模式 ,观察者模式有两个概念,1.观察者、被观察者。2.被观察者做出相应得动作,观察者能接收到。不分析设计模式,学习下spring中的事件机制实际开发如何使用 及使用场景 。

spring中的事件机制涉及到者几个类文件 :ApplicationEvent(事件类型)、ApplicationListener(事件监听类)、ApplicationEventPublisher(事件发布类)。先看看这几个类的继承、实现关系:

Application类继承jdk Utill包中的 EventObject,下面实现了很多子类:

ApplicationListener :接口继承了utill 包中的EventListener接口,泛型参数E必须继承ApplicationEvent类

 ApplicationEventPublisher: 事件发布接口 ,实现类很多,其中子类ApplicationContext,发布事件就用ApplicationContext类去发布 

使用方法:

  1.声明事件类型

public class DemoEvent extends ApplicationEvent{ 
    private static final long serialVersionUID = 1L; 
  
    public DemoEvent(Object source) { 
        super(source); 
    } 
  
} 

2.事件监听类

@Component  // 注意这里要把类注册到spring容器中
public class DemoListener implements ApplicationListener<DemoEvent> {//1 
     @Override
    public void onApplicationEvent(DemoEvent event) {//2 
         Object o = event.getSource();
        System.out.println("我(bean-demoListener)接收到了bean-demoPublisher发布的消息:"+ o); 
  
    } 
  
}

 3.配置类

@Configuration  
@ComponentScan("springboot.springboot_learn.event") //扫描加载bean文件
public class EventConfig { 
  
}

4.事件发布 ,使用AnnotationConfigApplicationContext 类,这个为ApplicationContext的子类

public class Client {
    public static void main(String[] args) throws InterruptedException {
        AnnotationConfigApplicationContext context = 
                new AnnotationConfigApplicationContext(EventConfig.class); 
        
        context.publishEvent(new DemoEvent("我要发财"));
      
    }
}

 实际开发中使用场景 :提交一个订单order,成功后给用户发送短信,大多时候我们会写类似一下代码

public String submitOrder(OrderInfo orderinfo){
      ... // 省略代码
      String rsMassage = dao.add(orderinfo);//插入信息
      Boolean flag  = sendSms(rsMassage); //发送短信
      return flag ; //返回是否成功
  }

这个代码一看是没有毛病。但是如果后续老板叫你,发送成功后还要给用户发个微信,还要给用户发个QQ...?,那么就要往submitOrder方法继续的添加代码,根据代码的开闭原则,这并不是最好的做法。那么可以做到,不修改代码,做到添加业务逻辑吗?利用spring的事件机制改造代码设计模式来实现。

1.申明事件类型

public class OrderEvent extends ApplicationEvent{
    private static final long serialVersionUID = 1L;

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

2.申明事件监听

@Component
class
WeiChatListener implements ApplicationListener<OrderEvent>{ @Override public void onApplicationEvent(OrderEvent event) { System.out.println("微信发送短信:" + event.getSource()); } }

3.发布事件

 @Autowired 
 ApplicationContext applicationContext; //1  
  public String submitOrder(OrderInfo orderinfo){
      ... // 省略代码
      String rsMassage = dao.add(orderinfo);//插入信息
      applicationContext.publishEvent(new OrderEvent("我要发财"));
      return "" ; //返回是否成功
  }

后来老板叫你还要加个普通的短信?现在怎么办 ?修改代码吗 ?No 直接加个普通短信事件监听,注入实例到spring容器就ok了 ;

@Component
  class massageListener implements ApplicationListener<OrderEvent>{

    @Override
    public void onApplicationEvent(OrderEvent event) {
        System.out.println("发送不通短信:" + event.getSource());
    }
      
  }

还要加别的xxx短信 ?? 。ok继续加个Listener,是不是这样优秀多了 0-0

原文地址:https://www.cnblogs.com/jonrain0625/p/11192574.html