Spring 的事件监听机制(ApplicationEvent、ApplicationListener)

217 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

监听模式:

要素:

1.事件(Event):继承自 org.springframework.context.ApplicationEvent

2.监听器类(Listener): 实现 org.springframework.context.ApplicationListener

3.事件源(在spring中指的是事件发布) 是ApplicaitonContext

使用步骤:

1.定义事件:

public class MySpringApplicationEventForPay extends ApplicationEvent {

public MySpringApplicationEventForPay(PaymentInfo source) {
    super(source);
}

} 2.定义事件监听器类 @Component public class MySpringApplicationListenerForMail implements ApplicationListener { @Override public void onApplicationEvent(MySpringApplicationEventForPay event) { Object source = event.getSource(); System.out.println(source+"改变了. 【邮件事件监听器】将要做出响应....");

}

}

@Component public class MySpringApplicationListenerForSMS implements ApplicationListener {

@Override
public void onApplicationEvent(MySpringApplicationEventForPay event) {
    Object source = event.getSource();

    System.out.println(source+"改变了. 【短信事件监听器】将要做出响应....");
   
}

} 注意:定义事件event的时候,不需要用@Compoent注解,而定义监听器实现类的时候需要使用 @Component注解 3.发布事件

@Component public class PaymentService {

@Autowired
ApplicationContext applicationContext;

public void doService(){
    System.out.println(this.getClass().getName() +" 准备做出一些改变,这些改变将会影响到其他的地方");
    
    PaymentInfo paymentInfo = new PaymentInfo(123,"无所谓什么状态了,就是个测试而已");

    MySpringApplicationEventForPay event = new MySpringApplicationEventForPay(paymentInfo);

    applicationContext.publishEvent(event);//发布事件
    
}

} 注意:重点是在 要发布事件的地方,使用 如下代码发布事件,这样事件监听器类才能被触发做出响应

applicationContext.publishEvent(event);//发布事件 我个人的理解: PaymentService 就是事件源,只不过是在事件源里发布事件时候使用的是applicationContext进行发布的。

本利中额外使用的一个消息 承载对象

public class PaymentInfo {

private int id;
private String stauts;

public PaymentInfo(int id, String stauts) {
    this.id = id;
    this.stauts = stauts;
}
// 省略setter getter ....
@Override
public String toString() {
    return "PaymentInfo{" +
            "id=" + id +
            ", stauts='" + stauts + '\'' +
            '}';
}

} 4.测试代码

PaymentService paymentService = SpringUtil.getBean(PaymentService.class);

paymentService.doService(); Spring中提供了两个监听器类,一类是无序的,一类是有序的

无序监听器类 ApplicationListener :

public interface ApplicationListener extends EventListener 有序的监听器类 SmartApplicationListener:

public interface SmartApplicationListener extends ApplicationListener, Ordered