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

Spring使用@PropertySource加载YAML对象数组时nodes为null如何解决

解决方案

Spring完全支持读取YAML文件中的对象数组类型配置,你遇到的nodes属性为null是配置细节错误导致的,可按以下步骤排查修复:

  • 修正类名不匹配问题

检查@PropertySource注解中指定的factory属性值和你实际实现的YAML加载工厂类名是否一致,你当前代码中实现的工厂类名为YamlPropertySourceFactory,但注解内写的是YamlPropertyLoaderFactory.class,类名不一致会导致自定义工厂不生效,YAML文件无法被正确解析加载。

  • 为所有配置类添加Getter/Setter方法

Spring的@ConfigurationProperties绑定依赖属性的Getter和Setter方法完成值注入,你当前的MyNode类属性没有访问方法,CustomProperties的nodes属性也没有Getter/Setter,会导致绑定失败。可以通过引入Lombok的@Data注解简化代码,或者手动编写public修饰的Getter/Setter方法。
修正后的代码示例:

// MyNode类修正
import lombok.Data;
@Data
public class MyNode {
    private String label;
    private String id;
    private String uri;
}
// CustomProperties类修正
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.util.List;

@Data
@Component
@ConfigurationProperties(prefix = "main")
@PropertySource(value = "classpath:mycustomfile.yml", factory = YamlPropertySourceFactory.class)
public class CustomProperties {
    private List<MyNode> nodes;
}
  • 启用配置属性扫描

你需要在项目启动类上添加@EnableConfigurationProperties(CustomProperties.class)注解,显式启用对应配置类的绑定功能,避免Spring未扫描到配置类导致绑定不生效:

@SpringBootApplication
@EnableConfigurationProperties(CustomProperties.class)
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}
  • 检查YAML文件路径与格式

确认mycustomfile.yml文件确实放置在项目的resources根目录下,且YAML缩进统一使用空格而非Tab符,避免格式解析错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 20:24:02