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

为什么Spring Boot用@ConfigurationProperties无法绑定YAML列表到实体?

解决方案

你遇到的问题由几个配置错误共同导致,按以下步骤逐一修正即可:

  1. 修正@ConfigurationProperties注解配置
    @ConfigurationProperties需要指定配置前缀,匹配你YAML中配置的层级。你当前YAML的配置节点是顶级的sites,有两种修正方式:
  • 方式一(不修改现有YAML结构):
@ConfigurationProperties(prefix = "")
public class ApplicationProperties {
    @Getter
    @Setter
    private List<Site> sites;
}
  • 方式二(更规范,避免配置冲突):
    先修改YAML,给配置加统一前缀:
app:
  sites:
    - url: http://someurl1.com
      name: somename1
    # 其余站点配置保持不变

再修改配置类:

@ConfigurationProperties(prefix = "app")
public class ApplicationProperties {
    @Getter
    @Setter
    private List<Site> sites;
}
  1. 开启配置属性类的注册
    Spring默认不会自动识别@ConfigurationProperties修饰的类,需要手动开启注册,二选一即可:
  • 方式一:在Spring Boot启动类上添加@EnableConfigurationProperties(ApplicationProperties.class)注解
  • 方式二(Spring Boot 2.2+版本支持):在ApplicationProperties类上额外添加@Configuration或者@Component注解,或者在启动类上添加@ConfigurationPropertiesScan注解扫描配置类所在包
  1. 修正IndexBuilder类的注解错误
    你之前的用法完全误用了@Configuration和@Bean注解:
  • @Configuration是用来定义配置类的,不是普通业务类的注解
  • @Bean修饰的方法会在Spring启动时自动执行,用来向容器注册Bean实例,所以才会出现启动就自动调用run方法的问题

正确的修改方式:

// 添加@Component注解,把IndexBuilder交给Spring容器管理,才能正常注入依赖
@Component
public class IndexBuilder {
    @Autowired
    private ApplicationProperties properties;

    public void run() {
        System.out.println(properties.getSites());
    }
}

后续你需要调用run方法时,直接从Spring容器中获取IndexBuilder的实例调用即可,不会再出现启动自动执行的问题。

  1. 额外注意项
    你的Site类作为配置绑定的载体,需要保证存在无参构造函数,建议额外添加Lombok的@NoArgsConstructor注解避免序列化绑定失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:54:01