Spring Boot从application.yml注入List<Map>配置得到空列表如何解决
正确注入List
错误原因
你现在的写法存在3个核心问题:
@ConfigurationProperties的使用逻辑错误:prefix指向了要注入的列表本身的key,且没有给Spring提供可写入的属性载体- 标注注解的方法没有被Spring识别为Bean,无法完成属性绑定
- 缺少对应属性的setter方法,Spring无法将读取到的配置写入返回的集合对象
正确实现方式
方案1:单独定义配置类(推荐)
1. 保留原有application.yml配置不变
cacheConfigs: - cacheOne: test: test1 - cacheTwo: test: test2 - cacheThree: test: test3 - cacheFor: test: test4
2. 编写配置属性类
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.List; import java.util.Map; @Component @ConfigurationProperties(prefix = "") // 不指定前缀,直接匹配顶层配置key public class CacheConfig { // 属性名必须和yml中的顶层key完全一致 private List<Map<String, String>> cacheConfigs; // 必须提供Getter和Setter,Spring通过Setter注入配置值 public List<Map<String, String>> getCacheConfigs() { return cacheConfigs; } public void setCacheConfigs(List<Map<String, String>> cacheConfigs) { this.cacheConfigs = cacheConfigs; } }
3. 开启配置属性扫描
在启动类上添加@EnableConfigurationProperties注解:
@SpringBootApplication @EnableConfigurationProperties public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
4. 注入使用
@Autowired private CacheConfig cacheConfig; // 直接获取配置值 List<Map<String, String>> configs = cacheConfig.getCacheConfigs();
方案2:直接注册为Bean(无需单独配置类)
如果你不想单独定义配置类,可以直接在配置类中声明Bean:
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.ArrayList; import java.util.List; import java.util.Map; @Configuration @EnableConfigurationProperties public class AppConfig { @Bean @ConfigurationProperties(prefix = "cache-configs") // Spring自动兼容驼峰和短横线写法 public List<Map<String, String>> cacheConfigs() { return new ArrayList<>(); } }
注入时直接注入这个List类型的Bean即可:
@Autowired private List<Map<String, String>> cacheConfigs;
注意事项
- 建议引入
spring-boot-configuration-processor依赖,IDE会提供配置项自动补全提示 - 如果用Lombok,可以给配置类加
@Data注解,省略手写Getter/Setter的代码 - 配置key的命名支持驼峰、短横线、下划线三种格式,Spring会自动完成格式转换匹配
内容的提问来源于stack exchange,提问作者yurii.pitomets
相关产品推荐
相关产品推荐

