1

When autowiring my spring test class with the JUnit4 Test Runner the context startup yields the following exception:

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)}

My Setup

The TestClass is annotated as followed

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/testContext.xml"})

The autowired fields are annotated like this

 @Autowired
 ACrudRepository repository; // is autowired

 @Autowired
 @Qualifier("service")
 ServiceClass service; // is NOT autowired

The testContext.xml has the following Bean definition (and some more):

<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"/>

What I have tried:

xetra11
  • 4,474
  • 6
  • 39
  • 98
  • 1
    try adding `autowire="byName"` in` `.along with @Qualifier("service") on your autowired bean – Nawnit Sen Nov 16 '18 at 15:39
  • Does not work unfortunately – xetra11 Nov 16 '18 at 15:42
  • 1
    where is your testContext.xml file? – Nawnit Sen Nov 16 '18 at 15:50
  • @NawnitSen it is placed within the `test/resources/spring/testContext.xml` directory. As mentioned in the question the `` is found and it's beans are injected. Therefore the `testContext.xml` should be fine – xetra11 Nov 16 '18 at 15:53
  • can you try doing it using java configuration once rather than using xml file? or maybe this could help "https://github.com/sbrannen/spring-test-junit5/issues/6" – Nawnit Sen Nov 16 '18 at 16:02

1 Answers1

1

The problem in this projekt (which was not mentioned here) was the <tx:annotation-driven/> tag and @Transactional annotation in the autowired bean. This annotation usualy uses java interface-based-proxy which can not be autowired, because they are not of the same type of the class.

To Fix this we used the tag <tx:annotation-driven proxy-target-class="true"/>.

Much thanks to this answer: https://stackoverflow.com/a/19624412

ooyen
  • 101
  • 1
  • 8