如何测试从application.properties取值的同一类多Bean实例的创建
问题解决步骤
1. 修正@ConfigurationProperties注解位置
你当前把@ConfigurationProperties(prefix = "healthcheck")标注在了测试类上,这个注解不能作用于测试类,需要移到对应的配置类上:
- 如果是
AppHealthCheckProperties作为属性绑定类,把该注解加在AppHealthCheckProperties类定义上 - 如果是
AdapterHealthCheckConfig负责接收列表配置,把该注解加在AdapterHealthCheckConfig类定义上
2. 开启配置属性绑定功能
在你的AppHealthCheckConfig配置类上添加@EnableConfigurationProperties注解,指定需要绑定的属性类:
@Configuration @EnableConfigurationProperties(AppHealthCheckProperties.class) public class AppHealthCheckConfig { // 原有@PostConstruct逻辑保持不变 }
如果使用Spring Boot 2.2+版本,也可以直接给属性类加@ConfigurationProperties注解,同时在启动类/测试类上添加@ConfigurationPropertiesScan扫描属性类所在包。
3. 修正测试类注解冗余和冲突
你同时使用了@SpringBootTest和@ContextConfiguration,合并配置避免冲突,同时移除测试类上无效的@ConfigurationProperties注解:
@ActiveProfiles("test") @ExtendWith({SpringExtension.class, MockitoExtension.class}) @SpringBootTest(classes = {AppHealthCheckContributor.class, AppHealthCheckProperties.class, AppHealthCheckConfig.class}) @TestPropertySource(locations = "classpath:application-test.properties") class AppHealthCheckConfigTest { // 原有测试逻辑保持不变 }
注意@TestPropertySource的路径要加classpath:前缀,避免找不到配置文件。
4. 检查属性类和配置文件格式
- 确认
AppHealthCheckProperties类提供了全属性的setter方法,或添加了Lombok的@Data/@Setter注解 - 确认
application-test.properties里的配置格式正确,示例:
healthcheck.app[0].name=testHealthIndicator healthcheck.app[0].baseUrl=http://localhost healthcheck.app[0].basePath=/test
- 确认
AdapterHealthCheckConfig里的apps字段类型是List<AppHealthCheckProperties>,字段名和配置里的app匹配(如果字段名是apps,需要加@JsonProperty("app")或者调整配置前缀为healthcheck.apps)
内容的提问来源于stack exchange,提问作者du-it
相关产品推荐
相关产品推荐

