Spring中的监听器

爱被打了一巴掌 2022-03-08 03:36 283阅读 0赞

Spring中的监听器

  • 问题描述
  • 事件类
  • 监听器类
  • 对应的controller
  • 实体类
  • 测试效果

问题描述

现在项目中有一个报表生成的模块,以前的做法是用了一个死循环,每隔几秒钟去生成一次;就想换一种做法,想到了spring的监听器。此demo中我为了方便,用的是springboot,ssm项目中完全一样。

事件类

首先要有一个事件,这个事件用于区别你的操作、比如删除、增加都对应一个事件。

  1. /**
  2. * 事件类,继承ApplicationEvent
  3. */
  4. public class StudentAddEvent extends ApplicationEvent {
  5. private Student student;
  6. public StudentAddEvent(Object source,Student student) {
  7. super(source);
  8. this.student=student;
  9. }
  10. public String getInfo() {
  11. return student.toString();
  12. }
  13. }

监听器类

有了事件还不够,还必须要有一个监听器去监听该事件

  1. /**
  2. * 事件监听器类,实现ApplicationListener,传入一个泛型类,
  3. * 如果不传,需要手动判断是否是你需要的事件类型
  4. */
  5. @Component
  6. public class StudentAddListener implements ApplicationListener<StudentAddEvent> {
  7. @Override
  8. public void onApplicationEvent(StudentAddEvent studentAddEvent) {
  9. String info = studentAddEvent.getInfo();
  10. System.out.println("增加的学生信息:" + info);
  11. }
  12. }

对应的controller

需要实现ApplicationContextAware,为了拿到ApplicationContext 对象,调用publishEvent发布事件;实现ApplicationContextAware这个接口之后,当spring加载完成该controller之后就会调用setApplicationContext方法,此时,将会拿到ApplicationContext 对象。

  1. @RestController
  2. public class SecController implements ApplicationContextAware{
  3. private static ApplicationContext applicationContext;
  4. @RequestMapping("sec")
  5. public String sec(String name,Integer age){
  6. Student student = new Student();
  7. student.setAge(age);
  8. student.setName(name);
  9. this.addStudent(student);
  10. return "sec";
  11. }
  12. @Override
  13. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  14. System.out.println("启动成功");
  15. this.applicationContext = applicationContext;
  16. }
  17. public void addStudent(Student student){
  18. StudentAddEvent addEvent = new StudentAddEvent(this, student);
  19. applicationContext.publishEvent(addEvent);
  20. }
  21. }

实体类

  1. public class Student {
  2. private String name;
  3. private Integer age;
  4. public String getName() {
  5. return name;
  6. }
  7. public void setName(String name) {
  8. this.name = name;
  9. }
  10. public Integer getAge() {
  11. return age;
  12. }
  13. public void setAge(Integer age) {
  14. this.age = age;
  15. }
  16. @Override
  17. public String toString() {
  18. return "Student{" +
  19. "name='" + name + '\'' +
  20. ", age=" + age +
  21. '}';
  22. }
  23. }

测试效果

在浏览器输入 http://localhost:8080/sec?name=”zhangsan”&age=20,
控制台会打印

增加的学生信息:Student{name=’“zhangsan”’, age=20}

发表评论

表情:
评论列表 (有 0 条评论,283人围观)

还没有评论,来说两句吧...

相关阅读

    相关 spring容器监听器

    spring容器监听器(初始化redis数据) redis缓存 一个完整redis缓存操作包括3个步骤 1.缓存数据库初始化(预热)[将数据库数据加

    相关 spring boot -- 监听器

    一些系统配置,存储在数据库中,需要在项目启动时加载进缓存。此时可以实现ApplicationListener类来实现监听。 第一步: package com.lic

    相关 Java监听器

    1、概念          Servlet中的listener的作用是通过监听一些事件的发生,listener在事件发生前后可以做一些必要的处理。   2、原理