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

运行SpringBootTest时@Qualifier指定Bean未注入、配置属性不生效问题

问题根因与解决方案

核心问题说明

  • 测试类使用MockitoJUnitRunner,该Runner仅支持Mockito的Mock能力,不会加载Spring上下文,因此@SpringBootTest、配置文件加载、Bean注入相关的注解全部不生效
  • FDAccounts类存在三处错误,本身就会导致注入失败:
    • @Autowired注解拼写错误,原代码写为@Autowrired
    • 构造方法上的@Qualifier注解参数没有加字符串引号,不符合Java注解语法要求
    • 构造方法内部赋值逻辑错误,你写的是this.restTemplate = restTemplate,实际应该把入参rt赋值给成员变量
  • 测试类中的FDAccounts实例没有加@Autowired注解,手动声明的未初始化对象属性自然全为null
  • ApplicationProperties要生效需要在类上添加@ConfigurationProperties注解,同时配置类要加@EnableConfigurationProperties开启配置绑定

修正后的代码

第一步:修正FDAccounts.java

@Service
class FDAccounts{

     @Autowired
     private ApplicationProperties appProperties;

     private RestTemplate restTemplate;

     // 修正@Qualifier加引号、修正构造方法赋值逻辑
     public FDAccounts(@Qualifier("accountRestTemplate") RestTemplate rt){
           this.restTemplate = rt;
     }

    public void getAccount(){
       // 调用逻辑
       restTemplate.exchange(....);
    }

}

第二步:修正ApplicationProperties配置

确保ApplicationProperties类上添加了@ConfigurationProperties注解,示例:

// prefix替换为你实际的配置前缀
@ConfigurationProperties(prefix = "your.config.prefix")
public class ApplicationProperties {
    // 你的配置属性定义
}

同时在配置类(比如AccountBeans.java)上添加@EnableConfigurationProperties(ApplicationProperties.class)开启配置自动绑定。

第三步:修正测试类

// 替换Runner为SpringRunner,才能加载Spring上下文
@RunWith(SpringRunner.class)
@TestPropertySource(locations="classpath:application-test.yml")
// 可选:添加@ActiveProfiles("test")更适配SpringBoot的配置文件加载规则
@ActiveProfiles("test")
@SpringBootTest
class TestFDAccounts{
 
   // 注入FDAccounts实例,不要手动创建
   @Autowired
   private FDAccounts fdaAccounts;

   @Before
   public void setup(){
       // 有需要Mock的Bean可以在这里初始化,无需求可留空
   }

   @Test
   public void getAccounts(){
     fdaAccounts.getAccount();
     // 后续断言逻辑
   }

}

验证

做完以上修改后启动测试:

  • Spring上下文会正常加载,AccountBeans中定义的accountRestTemplate Bean会自动注入到FDAccounts的构造方法中
  • application-test.yml中的配置会自动绑定到ApplicationProperties的对应属性上,不会再出现null的情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 05:15:03