在 YAML 配置文件中定义 List 并在 Spring 应用中注入是非常常见的操作,下面详细介绍具体写法和注入方式。
一、YAML 中定义 List 的几种方式
1. 缩进式写法(推荐)
最常用的方式,通过短横线 -
加空格表示列表项:
yaml
# application.yml
my:
# 基本类型List 这种写法 要注意-后面不能有空格
stringList:
-苹果
-香蕉
-橙子
# 数字类型List 这种写法 要注意-后面不能有空格
numberList:
-10
-20
-30
# 对象类型List
userList:
-name: 张三
age: 25
-name: 李四
age: 30
-name: 王五
age: 35
2. 行内式写法(紧凑格式)
逗号分隔列表项:
yaml
# 行内式写法
my:
stringList: 苹果, 香蕉, 橙子
numberList: 10, 20, 30
# 对象列表行内式
userList: [{name: 张三, age: 25}, {name: 李四, age: 30}]
3. 混合写法
根据场景灵活组合:
yaml
my:
mixedList:
- 基础值
- {key: value} # 行内对象
-
name: 测试
value: 123 # 缩进对象
二、在 Spring 中注入 List 的方法
假设我们有如下配置类和实体类用于接收注入:
1. 实体类定义(用于对象列表)
java
运行
@Data
public class User {
private String name;
private Integer age;
}
2. 注入方式一:@Value 注解(适合简单类型)
java
运行
@Component
public class ListConfig {
// 注入字符串列表
@Value("${my.stringList}")
private List<String> stringList;
// 注入数字列表
@Value("${my.numberList}")
private List<Integer> numberList;
// 打印列表内容
public void printLists() {
System.out.println("字符串列表: " + stringList);
System.out.println("数字列表: " + numberList);
}
}
3. 注入方式二:@ConfigurationProperties(适合复杂类型)
更推荐的方式,支持对象列表和类型转换:
java
运行
@Component
@ConfigurationProperties(prefix = "my") // 绑定前缀
@Data
public class MyConfig {
private List<String> stringList;
private List<Integer> numberList;
private List<User> userList; // 对象类型列表
}
4. 使用注入的 List
java
运行
@SpringBootApplication
public class ListDemoApplication implements CommandLineRunner {
@Autowired
private MyConfig myConfig; // 注入配置类
@Autowired
private ListConfig listConfig; // 注入@Value配置
public static void main(String[] args) {
SpringApplication.run(ListDemoApplication.class, args);
}
@Override
public void run(String... args) {
// 打印@ConfigurationProperties注入的列表
System.out.println("用户列表: " + myConfig.getUserList());
// 打印@Value注入的列表
listConfig.printLists();
}
}
三、注意事项
配置前缀匹配:
- @ConfigurationProperties 的 prefix 要与 yaml 中的父节点完全匹配
- 字段名要与 yaml 中的子节点名称一致(支持驼峰命名转换)
依赖添加:
如果使用 @ConfigurationProperties,需要在 pom.xml 中添加依赖(Spring Boot 项目):xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
类型转换:
Spring 会自动进行类型转换,如字符串转数字、日期等,但要确保格式正确默认值设置:
可以通过@Value("${my.list:默认值1,默认值2}")
或在配置类中直接初始化设置默认值
通过以上方式,就可以在 YAML 中灵活定义各种类型的 List,并在 Spring 应用中方便地注入和使用了。