1.ApplicationContext实现了ApplicationEventPublisher接口,是能发布事件的必要条件;
2.ApplicationContextEvent 类继承了ApplicationEvent类(非必要条件);
package com.dj;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.bind.annotation.RestController;
import java.io.Serializable;
/**
* @Author: ldj
* @Date: 2021/12/17/18:28
* @Description:
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@RestController
@Slf4j
public class PublishEventDemo {
/**
* 使用ApplicationContext发布事件
*/
@Autowired
ApplicationContext applicationContext;
@Test
public void sendData() {
//1.构造事件类信息,加@Builder才可以这样
UserDTO userDTO = UserDTO.builder()
.name("ldj")
.age(18)
.sex("男")
.build();
//2.开始发布事件
applicationContext.publishEvent(userDTO);
}
}
/**
* 事件类
* 1.不实现序列化也不会报错!!!!
* 2.如果不加@Data 监听到信息:com.dj.UserDTO@b7d2d51
*/
@Data
@Builder
class UserDTO implements Serializable{
private String name;
private Integer age;
private String sex;
}
/**
* 监听器类
*/
@Slf4j
@Component
class MyEventListener{
@Asysc //可以选择异步执行(特别适合日志记录,别忘了在启动类加上@EnableAsync)
@EventListener //监听注解 可省略了(MyEventListener implements ApplicationListener<UserDTO>)
public void listen(UserDTO userDTO) {
log.info("MyEventListener监听到信息:{}", userDTO);
}
}
测试结果
回过头说开头第2条说明,网上大多数帖子将 事件类继承ApplicationEvent,其实并不是硬性条件,为什么?当你点进去看源码,就豁然开朗了