非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
相关产品推荐
相关产品推荐

