当前位置: 首页 > news >正文

SpringBoot使用自定义事件监听器的demo

记录一下SpringBoot自定义事件监听器的使用方法

案例源码:SpringBoot使用自定义事件监听器的demo

使用的SpringBoot2.0.x版本

<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.5.RELEASE</version><relativePath/> <!-- lookup parent from repository -->
</parent>

自定义事件监听: 自定义事件 和 自定义监听两部分

自定义事件
继承自ApplicationEvent抽象类,定义自己的构造器

自定义监听
实现ApplicationListener接口,然后实现onApplicationEvent方法

首先自定义事件
ApplicationEvent抽象类
myw
实现继承,用对象方式,新建对象

DemoUser.java

package boot.example.event.events;public class DemoUser {private String username;private String password;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}
}

EventDemoUser.java

package boot.example.event.events;import org.springframework.context.ApplicationEvent;public class EventDemoUser extends ApplicationEvent {private final DemoUser demoUser;public EventDemoUser(Object source, DemoUser demoUser) {super(source);this.demoUser = demoUser;}public DemoUser getDemoUser() {return demoUser;}
}

ApplicationListener接口
myw
自定义监听类
EventDemoUserListener.java

package boot.example.event.listener;import boot.example.event.events.EventDemoUser;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;//  将监听器装载入spring容器
@Component
//@Service
public class EventDemoUserListener implements ApplicationListener<EventDemoUser> {@Async@Overridepublic void onApplicationEvent(EventDemoUser eventDemoUser) {System.out.println("自定义事件监听器(EventDemoUserListener)收到发布的消息: " + eventDemoUser.getDemoUser().getUsername());System.out.println("自定义事件监听器(EventDemoUserListener)收到发布的消息: " + eventDemoUser.getDemoUser().getPassword());}
}

我这里使用接口的方式来触发
EventDemoUserController.java

package boot.example.event.controller;import boot.example.event.events.DemoUser;
import boot.example.event.events.EventDemo;
import boot.example.event.events.EventDemoUser;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;@RestController
@RequestMapping(value="/eventDemoUser")
public class EventDemoUserController {@Resourceprivate ApplicationContext applicationContext;@RequestMapping(value="/test1")public String test1() {DemoUser demoUser = new DemoUser();demoUser.setUsername("admin");demoUser.setPassword("123456");applicationContext.publishEvent(new EventDemoUser(this, demoUser));return "testEventDemo";}@Resourceprivate ApplicationEventPublisher applicationEventPublisher;@RequestMapping(value="/test2")public String test2() {DemoUser demoUser = new DemoUser();demoUser.setUsername("admin2");demoUser.setPassword("654321");applicationContext.publishEvent(new EventDemoUser(this, demoUser));return "testEventDemo";}}

这里使用了两种触发方式

@Resource
private ApplicationContext applicationContext;
@Resource
private ApplicationEventPublisher applicationEventPublisher;

控制台输出查看
myw
自定义监听的几种方式

1.启动时手动向ApplicationContext中添加监听器

EventDemo.java

package boot.example.event.events;import org.springframework.context.ApplicationEvent;public class EventDemo extends ApplicationEvent {public EventDemo(Object source) {super(source);}
}

AppEventDemo.java

package boot.example.event;import boot.example.event.listener.EventDemoListener1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableAsync;@SpringBootApplication
@EnableAsync
public class AppEventDemo {public static void main( String[] args ) {ConfigurableApplicationContext context = SpringApplication.run(AppEventDemo.class, args);// 手动向ApplicationContext中添加监听器context.addApplicationListener(new EventDemoListener1());System.out.println( "Hello World!" );}//  事件监听,自定义事件和自定义监听器类//  自定义事件:继承自ApplicationEvent抽象类,定义自己的构造器//  自定义监听:实现ApplicationListener接口,实现onApplicationEvent方法}

EventDemoListener1.java

package boot.example.event.listener;import boot.example.event.events.EventDemo;
import org.springframework.context.ApplicationListener;//  手动向ApplicationContext中添加监听器  不要@Component注解就能监听到
public class EventDemoListener1 implements ApplicationListener<EventDemo> {@Overridepublic void onApplicationEvent(EventDemo eventDemo) {Object msg = eventDemo.getSource();System.out.println("自定义事件监听器(MyEventListener1)收到发布的消息: " + msg);}
}

2.使用@Component注解自动监听

EventDemoListener2.java

package boot.example.event.listener;import boot.example.event.events.EventDemo;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;//  将监听器装载入spring容器
@Component
public class EventDemoListener2 implements ApplicationListener<EventDemo> {@Overridepublic void onApplicationEvent(EventDemo eventDemo) {Object msg = eventDemo.getSource();System.out.println("自定义事件监听器(MyEventListener2)收到发布的消息: " + msg);}
}

3.在application.properties中配置监听器,可以不用注解

EventDemoListener3.java

package boot.example.event.listener;import boot.example.event.events.EventDemo;
import org.springframework.context.ApplicationListener;//  在application.properties中配置监听器,可以不用注解
public class EventDemoListener3 implements ApplicationListener<EventDemo> {@Overridepublic void onApplicationEvent(EventDemo eventDemo) {Object msg = eventDemo.getSource();System.out.println("自定义事件监听器(MyEventListener3)收到发布的消息: " + msg);}}

application.properties配置

context.listener.classes=boot.example.event.listener.EventDemoListener3

4.通过@EventListener注解实现事件监听(使用最方便)

EventDemoListener4.java

package boot.example.event.listener;import boot.example.event.events.EventDemo;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;//  通过@EventListener注解实现事件监听
@Component
public class EventDemoListener4 {@EventListenerpublic void listener(EventDemo eventDemo) {Object msg = eventDemo.getSource();System.out.println("自定义事件监听器(MyEventListener4)收到发布的消息: " + msg);}}

触发监听

EventDemoController .java

package boot.example.event.controller;import boot.example.event.events.EventDemo;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;@RestController
@RequestMapping(value="/eventDemo")
public class EventDemoController {@Resourceprivate ApplicationContext applicationContext;@RequestMapping(value="/test")public String test() {applicationContext.publishEvent(new EventDemo("测试监听事件"));return "testEventDemo";}
}

控制台查看 四种方式执行默认是有先后顺序的
myw
还有一种方式 这种方式使用更方便

DemoRole.java 和 DemoUser.java

package boot.example.event.events;public class DemoRole {private Integer roleId;private String roleName;public Integer getRoleId() {return roleId;}public void setRoleId(Integer roleId) {this.roleId = roleId;}public String getRoleName() {return roleName;}public void setRoleName(String roleName) {this.roleName = roleName;}
}
package boot.example.event.events;public class DemoUser {private String username;private String password;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}
}

监听类EventDemoListenerMultiple.java

package boot.example.event.listener;import boot.example.event.events.DemoRole;
import boot.example.event.events.DemoUser;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;@Component
//@Service
public class EventDemoListenerMultiple {@Async@EventListener(DemoUser.class)public void listenerDemoUser(DemoUser demoUser) {String name = demoUser.getUsername();System.out.println("listenerDemoUser---"+name);}@Async@EventListener(DemoRole.class)public void listenerDemoUser(DemoRole demoRole) {String name = demoRole.getRoleName();System.out.println("listenerDemoUser---"+name);}}

监听器触发类EventDemoMultipleController.java

package boot.example.event.controller;import boot.example.event.events.DemoRole;
import boot.example.event.events.DemoUser;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;@RestController
@RequestMapping(value="/eventDemo")
public class EventDemoMultipleController {@Resourceprivate ApplicationContext applicationContext;@RequestMapping(value="/demoUser")public String demoUser() {DemoUser demoUser = new DemoUser();demoUser.setUsername("admin");demoUser.setPassword("123456");applicationContext.publishEvent(demoUser);return "testEventDemo";}@Resourceprivate ApplicationEventPublisher applicationEventPublisher;@RequestMapping(value="/demoRole")public String demoRole() {DemoRole demoRole = new DemoRole();demoRole.setRoleId(4);demoRole.setRoleName("角色");applicationContext.publishEvent(demoRole);return "testEventDemo";}}

Servlet渐渐地淡出视野,也记录一下使用

CustomServletContextListener.java

package boot.example.event.config;import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;/***  servelt的监听器*/
@WebListener
public class CustomServletContextListener implements ServletContextListener {@Overridepublic void contextInitialized(ServletContextEvent sce) {//  SpringBoot WEB启动间执行一次System.out.println("CustomServletContextListener--contextInitialized");}@Overridepublic void contextDestroyed(ServletContextEvent sce) {//  SpringBoot WEB销毁执行System.out.println("CustomServletContextListener--contextDestroyed");}}

在启动类加上扫描注解

@ServletComponentScan("boot.example.event.config")

项目结构
myw

记录到此!

http://www.lryc.cn/news/119645.html

相关文章:

  • arcgis定义投影与投影
  • Flink多流处理之Broadcast(广播变量)
  • LVS/DR+Keepalived负载均衡实战(一)
  • 测试DWPose的onnx +Unity barracuda
  • 轻装上阵,不调用jar包,用C#写SM4加密算法【卸载IKVM 】
  • redis学习笔记(一)
  • 最优化问题 - 拉格朗日对偶
  • 关于ISO27701隐私信息安全管理体系介绍
  • C语言案例 分数列求和-11
  • Git 入门
  • PAT 1010 Radix
  • ruoyi-cloud微服务新建子模块
  • Dijkstra(求最短路)
  • React 脚手架
  • CTFSHOW php命令执行
  • 侧滑置顶,取消置顶
  • Pycharm解决启动时候索引慢的问题
  • Http请求响应时间一般划分标准
  • 生成测试报告,在Unittest框架中就是简单
  • 生成式人工智能的潜在有害影响与未来之路(一)
  • lightdb23.3 表名与包名不能重复
  • Oracle 开发篇+Java通过HiKariCP访问Oracle数据库
  • 进销存管理系统(小杨国贸)springboot采购仓库财务java jsp源代码mysql
  • 指针初阶(2)
  • 基于Gradio的GPT聊天程序
  • 包管理工具详解npm 、 yarn 、 cnpm 、 npx 、 pnpm(2023)
  • Terraform 系列-批量创建资源时如何根据某个字段判断是否创建
  • Android侧滑栏(一)可缩放可一起移动的侧滑栏
  • 简单程度与自负是否相关?探索STM32的学习价值
  • 第二章:CSS基础进阶-part3:弹性例子布局