详解Spring ApplicationEvent和ApplicationListener的用法

最近在写一个接口,是关于日志调用的。当第三方调用接口注册会员的时候,我们这边会做一个日志记录,这样就可以随时查看信息是否有异常。

于是,就用到了 Spring的ApplicationEvent和ApplicationListener。再次感受到了Spring的强大之处,Spring框架是企业级的,所以很多用法都已经包装好了的,我们拿过来使用就可以的。其实,刚开始的时候,我是不知道用什么程序去实现,正好我们项目之前也有同样的需求,我是看他们的源码,不懂的时候在网上了解一下,才知道是这么个回事。

为什么要使用ApplicationEvent和ApplicationListener?

Spring事件需要遵循以下程序,我们就按着这几个步奏一一道来:

(1)自定义事件:继承ApplicationEvent

(2)定义事件监听器:实现ApplicationListener

(3)使用容器发布事件

一、自定义事件-- 第一步就是说需要建实体类、表(这儿我就省略了哈);第二步就是让你的实体类去继承ApplicationEvent。如下

public class ResponseEvent extends ApplicationEvent {

    private ResponseLog responseLog;

    //  构造函数
    public ResponseEvent(Object source, ResponseLog responseLog) {
        super(source);
        this.ResponseLog = ResponseLog;
    }

    public ResponseLog getResponseLog() {
        return ResponseLog;
    }

    public void setResponseLog(ResponseLog ResponseLog) {
        this.ResponseLog = ResponseLog;
    }
}

 二、实现ApplicationListener。从单词上就可以明白,他是一个监听器,监听事件的成或败。

@Component
public class ResponseListen implements ApplicationListener {

    protected static final Logger log = Logger.getLogger(InterfaceResponseListen.class);

    @Autowired
    private ResponseLogService ResponseLogService;

    @Override
    @Async
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        if (!(applicationEvent instanceof InterfaceResponseEvent)) {
            return;
        }
        try {
            ResponseEvent interfaceResponseEvent = (ResponseEvent) applicationEvent;
            System.out.println("开始执行ResponseListen...");

            ResponseLog log = ResponseEvent.getResponseLog();
            if (log != null) {
                ResponseLogService.save(log);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e);
        }
    }
}

实现接口就要实现接口里面所有的方法。因此也就实现了唯一的onApplicationEvent()方法,最后是一个save()方法。如果运行成功的话,你的数据库会多一条数据的。

三、发布事件--我们会用到ApplicationContext(上下文环境,必须要使用到的)。主要是它继承自BeanFactory接口,除了包含BeanFactory的所有功能之外,在国际化支持、资源访问(如URL和文件)、事件传播等方面进行了良好的支持。

public void ResponseEvent(Object source, ResponseLog ResponseLog) {
        try {
            ApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
            ResponseEvent event = new ResponseEvent(source, ResponseLog);
            context.publishEvent(event);
        } catch (Exception e) {
            log.error("interfaceResponseEvent service error",e);
        }
    }

context.publishEvent()方法,就是把你的事件进行发布。

最后一步,就是需要你在你的Controller层,写你的业务逻辑。

大家有没有发现,我的代码里面,使用了几个有意思的注解,其中一个是

@Component,作用就是把pojo里面的bean放到容器里面,会自动包装。

还有一点就是当你在Controller里面写代码的时候,请求和相应的类的最上面加一个

@XmlRootElement注解(不加的话会报一个错误,会提示你需要加这个注解)。就像这样的
@XmlRootElement
public class ResponseData {

    private String serialNumber;
    private String cardNo;
    private String name;
    private String mobile;
   
    public String getSerialNumber() {
        return serialNumber;
    }

    public void setSerialNumber(String serialNumber) {
        this.serialNumber = serialNumber;
    }

    public void setCardNo(String cardNo) {
        this.cardNo = cardNo;
    }

    public String getCardNo() {
        return cardNo;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    
}

这样就可以 了。是不是感觉很简单。是不是认为很容易。第一次接触这个,确实有点难,当你试着去做下去的时候,你已经很厉害了,随着深入的了解,也会很快掌握了的。

猜你喜欢

转载自blog.csdn.net/weixin_41038852/article/details/82594315