spring发布和接收定制的事件(spring事件传播)

整理下原文方便阅读和复制代码测试

概述

有事件,即有事件监听器. 有人问你spring监听器有哪些你看了下文即也知道了。

事件传播
ApplicationContext基于Observer模式(java.util包中有对应实现),提供了针对Bean的事件传
播功能。通过Application. publishEvent方法,我们可以将事件通知系统内所有的
ApplicationListener。
事件传播的一个典型应用是,当Bean中的操作发生异常(如数据库连接失败),则通过事件传播
机制通知异常监听器进行处理。在笔者的一个项目中,就曾经借助事件机制,较好的实现了当系统
异常时在监视终端上报警,同时发送报警SMS至管理员手机的功能。

ApplicationContext容器提供了容器内部事件发布功能,是继承自JavaSE标准自定义事件类而实现的。

JavaSE标准自定义事件结构不在此详细描述,一张图很直观的描述清楚:
在这里插入图片描述
EventObject,为JavaSE提供的事件类型基类,任何自定义的事件都继承自该类,例如上图中右侧灰色的各个事件。Spring中提供了该接口的子类ApplicationEvent。

EventListener为JavaSE提供的事件监听者接口,任何自定义的事件监听者都实现了该接口,如上图左侧的各个事件监听者。Spring中提供了该接口的子类ApplicationListener接口。

JavaSE中未提供事件发布者这一角色类,由各个应用程序自行实现事件发布者这一角色。Spring中提供了ApplicationEventPublisher接口作为事件发布者,并且ApplicationContext实现了这个接口,担当起了事件发布者这一角色。但ApplicationContext在具体实现上有所差异,Spring提供了ApplicationEventMulticaster接口,负责管理ApplicationListener和发布ApplicationEvent。ApplicationContext会把相应的事件相关工作委派给ApplicationEventMulticaster接口实现类来做。类图如下所示:
在这里插入图片描述
事件发布时序图如下:
在这里插入图片描述
Spring事件处理一般过程:

◆定义Event类,继承org.springframework.context.ApplicationEvent。
◆编写发布事件类Publisher,实现org.springframework.context.ApplicationContextAware接口。
◆覆盖方法setApplicationContext(ApplicationContext applicationContext)和发布方法publish(Object obj)。
◆定义时间监听类EventListener,实现ApplicationListener接口,实现方法onApplicationEvent(ApplicationEvent event)。

  1. 发布
    1.1 事件的发布者需要实现的接口
    org.springframework.context.ApplicationEventPublisherAware
    1.2 代码示例
import org.springframework.context.ApplicationEvent;

public class TradeEvent extends ApplicationEvent {
    public TradeEvent(String source) {
        super(source);
    }
}

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.stereotype.Component;


@Component
public class TradeContextListener implements ApplicationListener {
    @Override
    public void onApplicationEvent(ApplicationEvent e) {
        System.out.println(e.getClass().toString());
        if (e instanceof ContextStartedEvent) {
            System.out.println("it was contextStartedEvent");
        }
        if (e instanceof TradeEvent) {
            System.out.println(e.getSource());
        }
    }
}
  1. 接受事件
    2.1需要实现的接口org.springframework.context.ApplicationListener
    2.2代码示例
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;

@Component
public class HelloWorld implements ApplicationEventPublisherAware {
    private String word="hello word";
    private ApplicationEventPublisher tradeEventPublisher;

    public void setWord(String w) {
        this.word = w;
    }

    public void say() {
        System.out.println("say : " + this.word);
        //construct a TradeEvent instance and publish it
        TradeEvent tradeEvent = new TradeEvent(new String("tradeEvent"));
        this.tradeEventPublisher.publishEvent(tradeEvent);
    }
    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher)
    {
        this.tradeEventPublisher = applicationEventPublisher;
    }
}
  1. 测试代码
import ***.HelloWorld;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
    @Autowired
    private HelloWorld helloWorld;

    @Test
    public void contextLoads() {
        helloWorld.say();
    }

}

Spring中ApplicationContext的事件机制— 内定事件)
在Spring中已经定义了五个标准事件,分别介绍如下:

  1. ContextRefreshedEvent:当ApplicationContext初始化或者刷新时触发该事件。

  2. ContextClosedEvent:当ApplicationContext被关闭时触发该事件。容器被关闭时,其管理的所有单例Bean都被销毁。

  3. RequestHandleEvent:在Web应用中,当一个http请求(request)结束触发该事件。

  4. ContestStartedEvent:Spring2.5新增的事件,当容器调用ConfigurableApplicationContext的Start()方法开始/重新开始容器时触发该事件。

  5. ContestStopedEvent:Spring2.5新增的事件,当容器调用ConfigurableApplicationContext的Stop()方法停止容器时触发该事件。

下面通过一个例子展示如何处理Spring内定的事件(例程3.8)。创建一个Java工程,添加Spring开发能力后,新建ioc.test包。在包中新建ApplicationEventListener类,实现ApplicationListener接口,在onApplicationEvent()方法中添加事件处理代码,如下:

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.ContextStoppedEvent;
import org.springframework.stereotype.Component;

@Component
public class ApplicationEventListener implements ApplicationListener {
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        //如果是容器刷新事件
        if (event instanceof ContextClosedEvent){
             System.out.println(event.getClass().getSimpleName() + " 事件已发生!");
             } else if(event instanceof ContextRefreshedEvent) {
             //如果是容器关闭事件
             System.out.println(event.getClass().getSimpleName() + " 事件已发生!");
             } else if(event instanceof ContextStartedEvent){
             System.out.println(event.getClass().getSimpleName() + " 事件已发生!");
             } else if(event instanceof ContextStoppedEvent){
             System.out.println(event.getClass().getSimpleName() + " 事件已发生!");
             }else{
             System.out.println("有其它事件发生:" + event.getClass().getName());
             }
        }
}

运行主类,控制台输出如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值