spring模块(六)spring监听器(1)ApplicationListener

2024-05-09 14:04

本文主要是介绍spring模块(六)spring监听器(1)ApplicationListener,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、介绍

1、简介

当某个事件触发的时候,就会执行的方法块。

当然,springboot很贴心地提供了一个 @EventListener 注解来实现监听。

2、源码: 
package org.springframework.context;import java.util.EventListener;
import java.util.function.Consumer;@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {void onApplicationEvent(E event);default boolean supportsAsyncExecution() {return true;}static <T> ApplicationListener<PayloadApplicationEvent<T>> forPayload(Consumer<T> consumer) {return (event) -> {consumer.accept(event.getPayload());};}
}
3、与其他Listener的区别

看下ApplicationListener与SpringApplicationRunListener、EventPublishingRunListener的区别和联系。前提:springboot是基于spring的,一个springboot应用其核心是调用了spring的SpringApplication.run()方法,也就是说,springboot是为简化spring开发进行的封装。现在我们来分析三者关系。

(1)SpringApplicationRunListener 和 EventPublishingRunListener是由springboot提供的,且EventPublishingRunListener是SpringApplicationRunListener 的唯一实现。

(2)ApplicationListener:是由spring提供的,监听目标是ApplicationEvent类或者其子类,所有定制化的事件都直接或间接的继承ApplicationEvent,也就是说,定制化的事件都是ApplicationEvent的子类,都是ApplicationListener监听器的监听目标,EventPublishingRunListener发布的定制化事件间接受ApplicationListener监听。

二、原理

ApplicationListener监听器本身是一个函数式接口,监听对象为ApplicationEvent事件的子类,ApplicationEvent事件本身是一个抽象类,它拥有各式各样的子类,这些子类就是定制化的事件,专门用于特定的场景。ApplicationEvent事件继承EventObject这个事件本体,EventObject事件本体是所有事件的基础,EventObject事件本体拥有一个protected transient Object source;这样一个Object类型的source属性,用于存放事件。

那这个事件数据是如何传递的呢?通过观察源码,我们发现,在事件类继承的层层嵌套链中,子类都需要通过super()方法调用父类的构造方法,通过在super()中传递事件参数可以实现事件数据的层层传递,最终传递到EventObject,然后,在EventObject的构造方法中就可以完成source属性的初始化,也就完成了事件的传递以及最终存储。

三、使用

1、监听器

两个步骤:先实现 ApplicationListener<E extends ApplicationEvent> 接口来自定义监听器;再注册监听器。注册监听器有以下几个方法:

(1)通过启动类注册
@SpringBootApplication
public class MyApplication {public static void main(String[] args) {//SpringApplication.run(MyApplication.class, args);//等价于上面的启动只不过把过程进行拆分,扩展了中间操作SpringApplication application = new SpringApplication(MyApplication.class);application.addListeners(new MyApplicationListener());application.run(args);}
}
(2)通过自动配置文件spring.factories文件注册
org.springframework.context.ApplicationListener=\com.classloader.listener.CustomeApplicationListener
(3)通过注解注册

直接在自定义监听器上加上@Component、@Configuration等注解注册,这是自定义监听器常用的方法。

注意:通过注解注册监听不到容器加载之前的事件。

@Component
public class CustomeApplicationListener implements ApplicationListener<ApplicationStartedEvent> , Ordered {@Overridepublic void onApplicationEvent(ApplicationStartedEvent applicationStartingEvent) {System.out.println("自定义监听器CustomeApplicationListener,监听springboot启动,监听EventPublishingRunListener发布的启动开始事件");}@Overridepublic int getOrder() {return 0;}
}
2、ApplicationEvent事件
2.1、spring的内置事件

 以ContextRefreshedEvent看下结构:可以看到最终都是 ApplicationEvent

package org.springframework.context.event;import org.springframework.context.ApplicationContext;public class ContextRefreshedEvent extends ApplicationContextEvent {public ContextRefreshedEvent(ApplicationContext source) {super(source);}
}package org.springframework.context.event;import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;public abstract class ApplicationContextEvent extends ApplicationEvent {public ApplicationContextEvent(ApplicationContext source) {super(source);}public final ApplicationContext getApplicationContext() {return (ApplicationContext)this.getSource();}
}
2.2、自定义事件

extends ApplicationEvent 自定义事件

public class MyEvent extends ApplicationEvent {private String time = new SimpleDateFormat("hh:mm:ss").format(new Date());private String msg;public MyEvent(Object source, String msg) {super(source);this.msg = msg;}public MyEvent(Object source) {super(source);}public String getTime() {return time;}public void setTime(String time) {this.time = time;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}
}
@Slf4j
@Component
public class MyTask implements ApplicationListener {private static boolean aFlag = false;@Overridepublic void onApplicationEvent(ApplicationEvent event) {if (event instanceof ContextRefreshedEvent) {log.info("监听到 ContextRefreshedEvent...");}if (event instanceof MyEvent) {log.info("监听到 MyEvent...");MyEvent myEvent = (MyEvent) event;System.out.println("时间:" + myEvent.getTime() + " 信息:" + myEvent.getMsg());}}
}

内置事件不需要手动触发,自定义监听事件需要主动触发,通过applicationContext.publishEvent(event)来触发,写法有:

(1)

@SpringBootApplication
public class TaskApplication {public static void main(String[] args) {ConfigurableApplicationContext run = SpringApplication.run(TaskApplication.class, args);MyEvent event = new MyEvent("event", "忙中岁月忙中遣,我本愚来性不移");// 发布事件run.publishEvent(event);}
}

(2) 常用方法

@SpringBootApplication
public class TaskApplication implements CommandLineRunner {public static void main(String[] args) {SpringApplication.run(TaskApplication.class, args);}@Resourceprivate ApplicationContext applicationContext;@Overridepublic void run(String... args) throws Exception {MyEvent event = new MyEvent("event", "忙中岁月忙中遣,我本愚来性不移");// 发布事件applicationContext.publishEvent(event);}
}

四、demo

pom:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>listener-demo</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.2.4</version><relativePath/></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency></dependencies>
</project>

启动类:

package com.listener.demo;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class ListenerApplication {public static void main(String[] args) {SpringApplication.run(ListenerApplication.class, args);}
}
1、内置事件
package com.listener.demo.listener;import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;@Slf4j
@Component
public class MyListener implements ApplicationListener<ContextRefreshedEvent> {@Overridepublic void onApplicationEvent(ContextRefreshedEvent event) {log.info("启动start...");}
}

启动项目控制台打印:

注意:有时会加个标志位,

@Slf4j
@Component
public class MyTask implements ApplicationListener<ContextRefreshedEvent> {private static boolean aFlag = false;@Overridepublic void onApplicationEvent(ContextRefreshedEvent event) {if (!aFlag) {aFlag = true;log.info("我已经监听到了");}}
}

因为web应用会出现父子容器,这样就会触发两次监听任务,所以需要一个标志位,保证监听任务(log.info(“我已经监听到了”))只会触发一次 。

2、自定义事件

如现在自定义一个注解,在controller接口加这个注解-->aop拦截获取相关信息,并触发事件监听-->在监听器中处理业务,如存储、发送mq等等。

(1)自定义注解

package com.listener.demo.annotation;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;// 声明注解作用于方法
@Target(ElementType.METHOD)
// 声明注解运行时有效
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLog {String url() ;String detail() ;
}
package com.listener.demo.controller;import com.listener.demo.annotation.MyLog;
import com.listener.demo.dto.UserDTO;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/user")
public class UserController {@MyLog(url = "/user/add",detail = "addUser")@RequestMapping("/add")public String add(UserDTO userDTO) {return "add success";}@MyLog(url = "/user/update",detail = "updateUser")@RequestMapping("/update")public String update() {return "update success";}
}

(2)DTO:

package com.listener.demo.dto;import lombok.Data;@Data
public class UserDTO {private String userName;private String userAccount;private Integer age;
}
package com.listener.demo.dto;import lombok.Builder;
import lombok.Data;@Data
@Builder
public class UserLogDTO {private String url;private String detail;
}

(3)aop:

package com.listener.demo.aop;import com.listener.demo.annotation.MyLog;
import com.listener.demo.dto.UserLogDTO;
import com.listener.demo.event.MyLogEvent;
import jakarta.annotation.Resource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;import java.lang.reflect.Method;@Aspect
@Component
public class LogAspect {@Resourceprivate ApplicationContext applicationContext;@Around(value = "@annotation(com.listener.demo.annotation.MyLog)")public Object around(ProceedingJoinPoint joinPoint) throws Throwable {Signature signature = joinPoint.getSignature();MethodSignature methodSignature = (MethodSignature) signature;Method targetMethod = methodSignature.getMethod();MyLog annotation = targetMethod.getAnnotation(MyLog.class);//非AuthVerify权限类注解,放开if (annotation == null) {return joinPoint.proceed();}//触发listenerUserLogDTO userLogDTO = UserLogDTO.builder().detail(annotation.detail()).url(annotation.url()).build();applicationContext.publishEvent(new MyLogEvent(userLogDTO));return joinPoint.proceed();}
}

(4)监听:

package com.listener.demo.event;import com.listener.demo.dto.UserLogDTO;
import org.springframework.context.ApplicationEvent;public class MyLogEvent extends ApplicationEvent {public MyLogEvent(UserLogDTO log) {super(log);}public UserLogDTO getSource() {return (UserLogDTO) super.getSource();}}
package com.listener.demo.listener;import com.listener.demo.dto.UserLogDTO;
import com.listener.demo.event.MyLogEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;@Slf4j
@Component
public class MyListener implements ApplicationListener<MyLogEvent> {@Overridepublic void onApplicationEvent(MyLogEvent event) {UserLogDTO source = event.getSource();log.info("监听到:url={},detail={}",source.getUrl(),source.getDetail());//其他处理,比如存储日志}
}

(5)测试:访问localhost:4444/listenerDemo/user/add?userName=zhangsan&userAccount=zs

控制台打印

这篇关于spring模块(六)spring监听器(1)ApplicationListener的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/973596

相关文章

Java的foreach语句

foreach语句是java5的新特征之一,在遍历数组、集合方面,foreach为开发人员提供了极大的方便。 foreach语句是for语句的特殊简化版本,但是foreach语句并不能完全取代for语句,然而,任何的foreach语句都可以改写为for语句版本。 foreach并不是一个关键字,习惯上将这种特殊的for语句格式称之为“foreach”语句。从英文字面意思理解fo

关于Java的数组的使用

关于一维数组的使用 代码示例一如下: package com;public class test_array {public static void main(String[] args){//1.如何定义 一个 数组//1.1数组的声明String[] names;int[] scores;//1.2数组的初始化://1.2.1静态初始化:初始化数组与数组元素赋值同时进行nam

关于Java的URL编程

前言: 1> URL(Uniform Resource Locator):统一资源定位符,它表示 Internet 上某一资源的地址。 通过 URL 我们可以访问 Internet 上的各种网络资源,比如最常见的 www,ftp 站点。 浏览器通过解析给定的 URL 可以在网络上查找相应的文件或其他资源。  2> URL的基本结构由5部分组成: <传输协议>://<主机名>:<端口号

Java的clone()方法使用详解

前言: 我们知道,在java的object类中,有这么一个方法clone(),这个方法有什么用呢?怎样才能正确地使用这个方法呢? 下面一一来进行阐述一下 clone()方法详解: 1>clone()方法的作用 顾名思义,clone()方法的作用就是克隆的意思,引入这个方法,这样就便于我们构建属于自己的一些本地对象副本。 这样我们就不用担心因为副本对象的引用而使原生的对象发生改变。

SpringMVC+Hibernate +MySql+ EasyUI实现CRUD

SpringMVC+Hibernate +MySql+ EasyUI实现CRUD 原文地址 http://my.oschina.net/xshuai/blog/345117

企业支付宝账号开发接口教程--JAVA-UTF-8(实际操作完善中...SpringMVC+JSP)

关于即时到账的开发。审核通过。简单测试如下。 希望看的可以收藏或者赞一下哦。 1.拥有自己的支付宝企业账号。去产品商店选择适合自己的方案。并签约合同。 2.选择合适的商家收款产品并去签约。填写相应的信息 3.在商家服务会有PID和KEY是关键的东西。 4.选择自己签约的产品类型,下载对应的接口api与测试代码 即时到账收款 --alipaydirect 网银支付 -

微信OAuth授权获取用户OpenId-JAVA(个人经验)

个人微信小程序 可扫码体验 本文更新有可能先在开源中国。地址为:https://my.oschina.net/xshuai/blog/293458 https://open.weixin.qq.com/ 这个是授权登陆自己网站的和我的这个是有区别的。 带评论昵称  才同意加QQ ‍鉴于老是有人问我。就更新一下了。 更新时间 2016年10月18日 修改了测试号权限不足导致授权获取信息抛

Discuz! Ucenter API for JAVA

my.oschina.net/xshuai/blog/280242原文地址  Discuz! Ucenter API for JAVA   使用自己的项目于discuz联合登陆注册。 源码和jar文件都在http://code.google.com/p/discuz-ucenter-api-for-java/  有。 我只测试了非中文的注册。中文注册可以去http://code.goog

有懂discuz的吗?我需要在我自己的系统注册一个账号的时候,也把当前注册的账号放在discuz的用户里面。应该怎么做呀。需要discuz和java的接口吗?需要更改哪些东西。

discuz-ucenter_api_for_java 有懂discuz的吗?我需要在我自己的系统注册一个账号的时候,也把当前注册的账号放在discuz的用户里面。应该怎么做呀。需要discuz和java的接口吗?需要更改哪些东西。 所有的代码 1.UC.java package com.fivestars.interfaces.bbs.api;import java.io.IO

2014年5月3日整理java笔试题+答案和自己的代码

一.选择题(每题1分) 1. jsp 有几个内置对象?( )(单选) A 5个 B 6个 C 9个 D 8个 2. 在JAVA中,如何跳出当前的多重嵌套循环?( ) (多选) A break B return C forward Dfinally 3. 四种会话跟踪技术,哪个范围最大?( ) (单选) A page B request C session Dapplication 4. java中