rabejens
rabejens

Reputation: 8122

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?

Upvotes: 8

Views: 35619

Answers (4)

Ramzi Guetiti
Ramzi Guetiti

Reputation: 132

I had the same issue and I could resolve the issue by adding component scan path to the Application class as below:

@ComponentScan(basePackages= {"xx.xx"}) 

Upvotes: 2

Ravi Macha
Ravi Macha

Reputation: 717

I think you need to add @Service in implementing class.. like

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

Upvotes: 4

rabejens
rabejens

Reputation: 8122

I figured out you can do the same with a javax.inject style DI:

@Named("myConcreteThing")
public class SomethingImpl implements Something { ... }

Where you want to inject it:

@Inject
@Named("myConcreteThing")
private Something _something;

This is correctly picked up by @EnableAutoConfiguration and @ComponentScan.

Upvotes: 4

Jens
Jens

Reputation: 69439

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

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

Upvotes: 5

Related Questions