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

SpringBoot测试中@ConfigurationProperties注入Map返回null如何解决?

解决方案

你缺失的核心是@ConfigurationProperties的绑定功能激活配置和测试配置文件的加载配置,按以下步骤补全即可:

  • 激活配置属性绑定能力:@Configuration和@ConfigurationProperties组合使用时,需要搭配@EnableConfigurationProperties注解才能触发配置值的自动绑定,你可以在测试类上直接加@EnableConfigurationProperties(KeyStoreConfig.class),也可以把ConfigurationPropertiesAutoConfiguration.class加入到@ContextConfiguration的classes列表中,触发SpringBoot的配置属性自动绑定逻辑。
  • 显式指定测试配置文件路径:默认单元测试会优先读取src/test/resources下的配置文件,如果你只有src/main/resources下的application.yaml,可以在测试类上加@TestPropertySource(locations = "classpath:application.yaml")显式指定加载路径,避免测试环境读取不到配置。
  • 如果你用的是SpringBoot 2.2及以上版本,也可以给KeyStoreConfig类加上@ConfigurationPropertiesScan注解,同时把该注解的扫描包路径配置到测试上下文,也能实现配置的自动绑定。

可运行的Spock测试类示例参考:

import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.TestPropertySource
import spock.lang.Specification
import javax.annotation.Resource

@SpringBootTest
@EnableConfigurationProperties(KeyStoreConfig.class)
@TestPropertySource(locations = "classpath:application.yaml")
class KeyStoreConfigTest extends Specification {

    @Resource
    private KeyStoreConfig keyStoreConfig

    def "验证keystore配置正常加载"() {
        expect: "keyStores属性不为空"
        keyStoreConfig.getKeyStores() != null
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 00:15:01