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

非Spring Boot项目用Spring DI做无Mock真实测试时注入Bean为null如何解决

问题根源及修复方案

你遇到的注入失败是多个配置写错共同导致的,按以下步骤修复即可:

1. 修复配置类Bean定义错误

你写的service1 Bean的返回类型错误声明为了Service2,导致Spring容器中不存在Service1类型的Bean,修改为正确的返回类型:

@Configuration
public class SpringBeansConfig {
    // 修复返回类型为Service1,之前错写为Service2
    @Bean
    public Service1 service1(Service2 service2) {
        return new Service1(service2);
    }

    @Bean
    public Service2 service2() {
        return new Service2();
    }
}

2. 修复测试类的配置类引用错误

你测试类中@ContextConfiguration指定的配置类是不存在的Config.class,实际你写的配置类名为SpringBeansConfig.class,同时修正测试方法内的变量名、方法名拼写错误:

@ExtendWith(SpringExtension.class)
// 替换为实际的配置类名
@ContextConfiguration(classes = { SpringBeansConfig.class })
public class Service1Test {
    @Autowired
    public Service1 sut;

    @Test
    public void myTest() {
        // 修复变量名和方法名拼写错误:之前调用的是不存在的service1变量+拼写错误的soSomething方法
        X result = sut.doSomething();
    }
}

可选优化

如果你不想手动写Bean声明,也可以在配置类上加@ComponentScan注解,指定你的Service1、Service2所在的包路径,Spring会自动扫描@Service注解的类注册为Bean,不需要单独写@Bean方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 10:12:03