0
点赞
收藏
分享

微信扫一扫

Java 事件

闲云困兽 2022-01-07 阅读 43
java

文章目录

1. 事件体student

@Data
public class Student {
    private String username;
    private Integer age;
}

2. 事件

public class StudentEvent extends ApplicationEvent  {

    @Getter
    Student student;

    public StudentEvent(Student student) {
        super(student);
        this.student = student;
    }
}

3. 监听器

@Component
public abstract class StudentListener implements ApplicationListener<StudentEvent> {

    @Override
    public void onApplicationEvent(StudentEvent event) {
        handle(event);
    }

    public abstract void handle(StudentEvent event);
}

4. 对监听到的事件具体处理类

@Component
public class StudentEventHandler extends StudentListener{

@Override
public void handle(StudentEvent event) {
    Student student = event.getStudent();
    System.out.println(student);
    //publishEvent(event)再次调用事件发布器
}

5. 测试

    @Test
    void eventTest(){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        // 注册自定义事件监听器
        context.addApplicationListener(new StudentEventHandler());
        // 启动上下文
        context.refresh();
        Student student = new Student();
        student.setUsername("czn");
        student.setAge(5);
        //发布事件
        context.publishEvent(new StudentEvent(student));
    }
举报

相关推荐

0 条评论