Spring中的监听器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jjkang_/article/details/88548120

问题描述

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

事件类

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

/**
 * 事件类,继承ApplicationEvent
 */
public class StudentAddEvent extends ApplicationEvent {
    private Student student;

    public StudentAddEvent(Object source,Student student) {
        super(source);
        this.student=student;
    }
    public String getInfo() {
        return student.toString();
    }
}

监听器类

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

/**
 * 事件监听器类,实现ApplicationListener,传入一个泛型类,
 * 如果不传,需要手动判断是否是你需要的事件类型
 */
@Component
public class StudentAddListener implements ApplicationListener<StudentAddEvent> {

    @Override
    public void onApplicationEvent(StudentAddEvent studentAddEvent) {
        String info = studentAddEvent.getInfo();
        System.out.println("增加的学生信息:" + info);
    }
}

对应的controller

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

@RestController
public class SecController implements ApplicationContextAware{
    private static ApplicationContext applicationContext;

    @RequestMapping("sec")
    public String sec(String name,Integer age){
        Student student = new Student();
        student.setAge(age);
        student.setName(name);
        this.addStudent(student);
        return "sec";
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("启动成功");
        this.applicationContext  = applicationContext;
    }

    public void addStudent(Student student){
        StudentAddEvent addEvent = new StudentAddEvent(this, student);
        applicationContext.publishEvent(addEvent);
    }

}

实体类

public class Student {
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

测试效果

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

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

猜你喜欢

转载自blog.csdn.net/jjkang_/article/details/88548120