rabejens rabejens - 2 months ago 28
Java Question

Spring Boot: "No qualifying bean of type... found" when autowiring concrete class

I am writing a component using Spring Boot and Spring Boot JPA. I have a setup like this:

The interface:

public interface Something {
// method definitions
}


The implementation:

@Component
public class SomethingImpl implements Something {
// implementation
}


Now, I have a JUnit test which runs with
SpringJUnit4ClassRunner
, and I want to test my
SomethingImpl
with this.

When I do

@Autowired
private Something _something;


it works, but

@Autowired
private SomethingImpl _something;


causes the test to fail throwing a
NoSuchBeanDefinitionException
with the message
No qualifying bean of type [com.example.SomethingImpl] 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)}


But in the test case, I want to explicitly inject my
SomethingImpl
because it is the class I want to test. How to I achieve this?

Answer

If you want a special bean you have to use the @Qualifier annotation:

@Autowired
@Qualifier("SomethingImpl")
private Something _something;