Spring Boot中如何正确加载含列表的YAML配置文件?
解决Spring Boot中YAML列表配置加载扁平化的问题
我之前在开发Spring Boot应用时也踩过YAML列表解析的坑,你的问题本质是YAML语法格式不规范导致Spring的解析器把列表错误扁平化了。咱们一步步来解决:
首先修正YAML的写法
你当前的写法:
x: - 1 - 2
这种格式不符合YAML的列表规范,解析器会把它当成一个包含"- 1 - 2"字符串的单个元素,或者直接解析出错。正确的列表写法有两种:
1. 多行缩进式(推荐,可读性强)
这是YAML最常用的列表写法,每个元素单独一行并缩进:
x: - 1 - 2
2. 内联方括号式(适合短列表)
如果想把列表写在同一行,要用方括号包裹元素:
x: [1, 2]
然后在Spring Boot中正确绑定配置
修正YAML后,有两种常见方式获取这个列表:
方式一:使用@ConfigurationProperties(推荐)
这种方式类型安全,适合复杂配置:
- 创建配置类:
@Configuration @ConfigurationProperties(prefix = "") // 因为你的key就是"x",前缀为空 public class AppConfig { private List<Integer> x; // 必须提供getter和setter,Spring才能完成绑定 public List<Integer> getX() { return x; } public void setX(List<Integer> x) { this.x = x; } }
- 在启动类开启配置属性支持:
@SpringBootApplication @EnableConfigurationProperties(AppConfig.class) public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } }
- 注入使用:
@RestController public class TestController { private final AppConfig appConfig; // 构造注入(推荐) public TestController(AppConfig appConfig) { this.appConfig = appConfig; } @GetMapping("/test") public List<Integer> getXList() { return appConfig.getX(); // 这里就能拿到正确的[1,2]列表 } }
方式二:直接通过Environment获取
如果只是临时获取配置,可以直接注入Environment:
@RestController public class TestController { private final Environment environment; public TestController(Environment environment) { this.environment = environment; } @GetMapping("/test") public List<Integer> getXList() { // 直接获取列表类型 return environment.getProperty("x", List.class); // 或者先获取数组再转列表 // Integer[] xArray = environment.getProperty("x", Integer[].class); // return Arrays.asList(xArray); } }
额外注意点
- YAML对缩进非常敏感,必须用空格(不能用Tab)缩进,通常推荐2个空格
- 如果你的列表元素是字符串,要注意特殊字符的转义
- 尽量避免混用不同风格的列表写法,保持配置文件的一致性
内容的提问来源于stack exchange,提问作者Juan Villalobos




