spring自定义事件监听器

1. 创建自定义事件


import org.springframework.context.ApplicationEvent;
import java.util.List;

public class CollectionCreateEvent extends ApplicationEvent {

    private List<String> fileList;
    
    public CollectionCreateEvent(Object source,List<String> fileList) {
        super(source);
        this.fileList = fileList;
    }

    public List<String> getFileList() {
        return fileList;
    }
}

2. 创建事件监听器

(1) 实现ApplicationListener接口;

(2) 使用@EventListener注解,@EventListener注解可以直接在方法上使用,以指定该方法为事件监听器。


import java.util.List;

@Component
public class DatasetListener {

    @Autowired
    private SysFileService fileService;

    @EventListener
    public void handleMyEvent(CollectionCreateEvent event) {
        //处理事件
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        List<String> fileList = event.getFileList();
        System.out.println(fileList.size());
        System.out.println(JSON.toJSONString(fileList));
        System.out.println(fileService);
    }
}

3. 创建事件发布者


@Component
public class EventPublish {
    @Autowired
    private ApplicationEventPublisher publisher;

    public void publishCreateCollection(List<String> fileList) {
        CollectionCreateEvent customEvent = new CollectionCreateEvent(this, fileList);
        publisher.publishEvent(customEvent);
    }
}

4. 异步监听

  1. 监听类加注解 @Async
    在这里插入图片描述
  2. 项目启动类加 @EnableAsync
  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值