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

Spring Boot 3.1.2中Record绑定@ConfigurationProperties属性为null问题

问题原因及解决办法

核心问题有两个:

1. 配置属性与Record参数名不匹配

Spring Boot配置属性绑定遵循驼峰转短横线的命名规则,同时会直接匹配Record的构造参数名称。你的配置里是machine.product,但Record中对应的参数是productProperties,两者无法对应,因此Spring无法将配置中的product节点绑定到productProperties字段,导致它为null。

同理,内部的locationProperties也和配置里的location不匹配,同时你还遗漏了配置中的port字段绑定。

2. 未启用配置属性类

Spring Boot不会自动识别带有@ConfigurationProperties的类,必须显式将其纳入Spring容器管理,否则无法注入到其他组件中。


修正方案

步骤1:修正Record的参数名称,匹配配置结构

调整Record的参数名,使其与配置中的节点名称完全对应,同时补上port字段:

@ConfigurationProperties(prefix = "machine")
@Component // 标记为Spring组件,让容器扫描并注册
public record MachineProperties(Product product) {
    public record Product(int port, Location location) {
        public record Location(String foo, String bar) {

        }
    }
}

步骤2:启用配置属性(二选一)

  • 方式一:上面的代码已经添加了@Component,Spring会自动扫描并注册这个配置属性类,同时完成配置绑定。
  • 方式二:如果不想给MachineProperties加@Component,可以在主启动类上添加@EnableConfigurationProperties注解:
@SpringBootApplication
@EnableConfigurationProperties(MachineProperties.class)
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}

验证

启动应用后,Other组件中注入的machineProperties就能正确获取到配置里的product、port、location等属性值了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 14:02:08