简体   繁体   中英

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

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

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

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 .

我认为你需要在实现类中添加@Service ..就像

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

我有同样的问题,我可以通过向Application类添加组件扫描路径来解决此问题,如下所示:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM