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

SpringBoot 2中YAML属性映射POJO测试失败问题排查

问题排查与解决方案

针对SpringBoot 2.7.11中YAML配置映射POJO始终为null的问题,可从以下几个关键点排查并修复:

1. 组件扫描范围检查

确保ConfigItems类所在的包被Spring Boot的组件扫描覆盖:

  • 若你的Spring Boot主应用类(带@SpringBootApplication)位于com.example.demo包,ConfigItems需放在该包或其子包下;
  • 若ConfigItems在外部包,需在主类添加@ComponentScan(basePackages = "对应包路径"),扩大扫描范围。

2. 简化注解组合

方案一:保留@Configuration注解

ConfigItems类上的@Configuration已将其注册为Spring Bean,无需在测试类重复添加@EnableConfigurationProperties:

修正后的ConfigItems.java

@Configuration
@ConfigurationProperties(prefix = "configItems")
@Getter
@Setter
public class ConfigItems {

  private List<Item> items;
  
  @Getter
  @Setter
  @NoArgsConstructor
  @AllArgsConstructor
  public static class Item {
    private String field1;
    private String field2;
  }
}

修正后的MapFromYamTest.java

@SpringBootTest
@ActiveProfiles("test")
public class MapFromYamlTest {
  
  @Autowired
  private ConfigItems configItems;

  @Test
  public void everythingMappedCorrectly() {
    assertNotNull(configItems, "Config is null");
    assertNotNull(configItems.getItems(), "Items list is null");
    assertEquals(2, configItems.getItems().size());
  }
}

方案二:移除@Configuration注解

去掉ConfigItems上的@Configuration,通过测试类的@EnableConfigurationProperties注册Bean:

修正后的ConfigItems.java

@ConfigurationProperties(prefix = "configItems")
@Getter
@Setter
public class ConfigItems {

  private List<Item> items;
  
  @Getter
  @Setter
  @NoArgsConstructor
  @AllArgsConstructor
  public static class Item {
    private String field1;
    private String field2;
  }
}

修正后的MapFromYamTest.java

@SpringBootTest
@EnableConfigurationProperties(value = ConfigItems.class)
@ActiveProfiles("test")
public class MapFromYamlTest {
  
  @Autowired
  private ConfigItems configItems;

  @Test
  public void everythingMappedCorrectly() {
    assertNotNull(configItems, "Config is null");
  }
}

3. 验证Lombok生效情况

确保项目已正确引入Lombok依赖,且IDE安装了Lombok插件:

  • Maven依赖配置:
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

若Lombok未生效,@Getter/@Setter无法生成对应方法,会导致配置绑定失败。

4. 确认测试配置加载

检查src/test/resources/application-test.yml路径和名称是否正确,@ActiveProfiles("test")是否生效。可在测试类中添加日志或打印配置项,验证配置文件是否被成功加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 22:13:33