当使用 JUnit4 测试运行器 Autowiring 我的 spring 测试类时,上下文启动会产生以下异常:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.mypackage.TestClass': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.mypackage.ServiceClass com.mypackage.TestClass.service;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mypackage.ServiceClass] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
我的设置
TestClass
注释如下
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/testContext.xml"})
Autowiring 字段的注释如下
@Autowired
ACrudRepository repository; // is autowired
@Autowired
@Qualifier("service")
ServiceClass service; // is NOT autowired
testContext.xml
具有以下 Bean 定义(以及更多):
<bean class="com.mypackage.ServiceClass" id="service">
<property name="someBoolean" value="false"/>
<property name="otherBoolean" value="false"/>
<property name="someList">
<list><value>withOneValue</value></list>
</property>
</bean>
<jpa:repositories base-package="com.mypackage"/>
我尝试过的:
-
@Qualifier("service")
- 已检查What is a NoSuchBeanDefinitionException and how do I fix it?
- 已检查NoSuchBeanDefinitionException using @Autowired in spring test
- 已添加
<component-scan>
在 xml 中带有@Service/@Component
上ServiceClass
- 已添加
@ComponentScan
上TestClass
最佳答案
此项目中的问题(此处未提及)是 <tx:annotation-driven/>
标签和@Transactional
Autowiring bean 中的注释。这个注解通常使用java基于接口(interface)的代理,它不能被 Autowiring ,因为它们不是类的同一类型。
为了解决这个问题,我们使用了标签 <tx:annotation-driven proxy-target-class="true"/>
。
非常感谢这个答案:https://stackoverflow.com/a/19624412
关于java - 尝试不同的解决方案后,使用 JUnit4 Runner 进行 Spring 测试不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53340945/