【发布时间】:2018-11-16 15:34:02
【问题描述】:
当使用 JUnit4 Test Runner 自动装配我的 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"})
自动装配的字段是这样注释的
@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
- 在 xml 中添加了
<component-scan>,在ServiceClass上添加了@Service/@Component - 在
TestClass上添加了@ComponentScan
【问题讨论】:
-
尝试将
autowire="byName"添加到``.along with @Qualifier("service") on your autowired bean -
不幸的是不能工作
-
你的 testContext.xml 文件在哪里?
-
@NawnitSen 它位于
test/resources/spring/testContext.xml目录中。如问题中所述,找到了<jpa:repositories base-package="com.mypackage"/>,并注入了它的bean。因此testContext.xml应该没问题 -
你可以尝试使用java配置一次而不是使用xml文件吗?或者这可能有助于“github.com/sbrannen/spring-test-junit5/issues/6”
标签: java junit4 spring-test