当前位置: 首页 > news >正文

SpringBoot使用@Autowired将实现类注入到List或者Map集合中

前言

最近看到RuoYi-Vue-Plus翻译功能 Translation的翻译模块配置类TranslationConfig,其中有一个注入TranslationInterface翻译接口实现类的写法让我感到很新颖,但这种写法在Spring 3.0版本以后就已经支持注入ListMap,平时都没有注意到这一块,故此记录一下这种写法。

翻译模块配置类

TranslationConfig这里是翻译配置初始化的地方

package com.ruoyi.framework.config;import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.TranslationType;
import com.ruoyi.common.translation.TranslationInterface;
import com.ruoyi.common.translation.handler.TranslationBeanSerializerModifier;
import com.ruoyi.common.translation.handler.TranslationHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** 翻译模块配置类** @author Lion Li*/
@Slf4j
@Configuration
public class TranslationConfig {@Autowiredprivate List<TranslationInterface<?>> list;@Autowiredprivate ObjectMapper objectMapper;@PostConstructpublic void init() {Map<String, TranslationInterface<?>> map = new HashMap<>(list.size());for (TranslationInterface<?> trans : list) {if (trans.getClass().isAnnotationPresent(TranslationType.class)) {TranslationType annotation = trans.getClass().getAnnotation(TranslationType.class);map.put(annotation.type(), trans);} else {log.warn(trans.getClass().getName() + " 翻译实现类未标注 TranslationType 注解!");}}TranslationHandler.TRANSLATION_MAPPER.putAll(map);// 设置 Bean 序列化修改器objectMapper.setSerializerFactory(objectMapper.getSerializerFactory().withSerializerModifier(new TranslationBeanSerializerModifier()));}}

可以看到在这个配置类中注入了一个List集合,其类型为TranslationInterface翻译接口

我们来看一下它的实现类

这些实现类定义在common模块的translation包下,分别是部门字典OSS用户名的翻译实现

Spring会扫描TranslationInterface翻译接口实现类注入到List

我们来Debug看一下效果,可以看到TranslationInterface翻译接口的实现类确实全部已经注入进来了

由于@Autowired注解还可以注入BeanMap中,这里我们手动加上Map集合,Debug断点调试一下:

http://www.lryc.cn/news/110437.html

相关文章:

  • 【linux目录的权限和粘滞位】
  • TP DP PP 并行训练方法介绍
  • P005 – Python操作符、操作数和表达式
  • SQL92 SQL99 语法 Oracle 、SQL Server 、MySQL 多表连接、Natural 、USING
  • 物联网平台使用笔记
  • Python-flask项目入门
  • 基于数据库 Sqlite3 的 root 管理系统
  • Hadoop 之 Hive 4.0.0-alpha-2 搭建(八)
  • vue3常用API之学习笔记
  • Python 程序设计入门(005)—— 字符串操作
  • 怎样将项目jar包放到服务器上
  • ruby调试
  • 【云原生】使用kubeadm搭建K8S
  • HCIE-Datacom真题和机构资料
  • 轮足机器人硬件总结
  • Flowable-网关-排他网关
  • GET 和 POST 的区别
  • FFmpeg中硬解码后深度学习模型的图像处理dnn_processing(一)
  • 计及需求响应和电能交互的多主体综合能源系统主从博弈优化调度策略(Matlab代码实现)
  • local-path-provisioner的使用(hostPath、local、local-path-provisioner三者对比)
  • 命令行快捷键Mac Iterm2
  • 无涯教程-Lua - Modules(模块)
  • url重定向
  • Linux 查看IP地址、子网掩码和网关的配置信息
  • token
  • 利用awk筛选给定时间范围内的日志
  • ORACLE字符集概念学习
  • 时间复杂度、空间复杂度实践练习(力扣OJ)
  • JMeter(二十四)、使用吞吐量控制器实现不同的用户操纵不同的业务
  • 8.1Jmeter5.1:Jmeter SSL