You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot使用@ConfigurationProperties读取配置返回空列表如何解决

问题排查与解决方案

核心问题点

  • 配置属性名与实体类字段名不匹配:配置中列表的key为abc.env[xxx],但配置属性类中对应的字段名为abcSources,SpringBoot配置绑定严格匹配前缀后的字段名,名称不匹配无法注入值。
  • 属性封装类字段与配置key不匹配,且缺失setter方法:配置中第二个属性为grant_type,但封装类中对应字段名为tokenGrantType,且该字段未提供setter方法,无法完成属性注入。
  • 配置属性类存在无效自注入:ReadAbcApplicationProperties类中自行注入自身的代码属于无效逻辑,无实际作用还可能引发循环依赖问题。
  • 未启用配置属性绑定(部分SpringBoot版本必现):未添加@EnableConfigurationProperties注解显式指定配置属性类,部分版本会出现属性绑定不生效的问题。

修复步骤

1. 修改配置属性类ReadAbcApplicationProperties

调整字段名与配置匹配,删除无效自注入代码:

@Component
@ConfigurationProperties(prefix = "abc")
public class ReadAbcApplicationProperties {
    // 字段名与配置中的env保持一致
    private List<AbcProperties> env = new ArrayList<>();

    public List<AbcProperties> getEnv() {
        return env;
    }

    public void setEnv(List<AbcProperties> env) {
        this.env = env;
    }
}

2. 修改属性封装类AbcProperties

调整字段名匹配配置key,补充缺失的setter方法:

public class AbcProperties {
    private String envname;
    // 驼峰命名适配配置中的grant_type,SpringBoot松绑定自动映射下划线到驼峰
    private String grantType;

    public String getEnvname() {
        return envname;
    }
    public void setEnvname(String envname) {
        this.envname = envname;
    }
    public String getGrantType() {
        return grantType;
    }
    // 补充setter方法
    public void setGrantType(String grantType) {
        this.grantType = grantType;
    }
}

3. 修改启动类

添加@EnableConfigurationProperties注解,调整取值方法对应修改后的字段:

@SpringBootApplication
// 显式启用配置属性绑定,指定对应的配置类
@EnableConfigurationProperties(ReadAbcApplicationProperties.class)
public class AbcApplication implements CommandLineRunner{
    private static Logger LOG = LoggerFactory.getLogger(AbcApplication.class);

    @Autowired
    ReadAbcApplicationProperties readAbcApplicationProperties;
    
    public static void main(String[] args) {
        SpringApplication.run(AbcApplication.class, args);
    }
    
    @Override
    public void run(String... args) {
        // 调用对应字段的getter方法取值
        LOG.info("values: {}", readAbcApplicationProperties.getEnv());
    }
}

修改完成后重新启动项目即可正常读取到配置的列表值。

内容的提问来源于stack exchange,提问作者Sweta Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 05:57:01