Spring的AppilcaitionContext发布事件和监听事件,最新

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,其实并不是硬性条件,为什么?当你点进去看源码,就豁然开朗了

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值