Spring 引导:"No qualifying bean of type... found" 自动装配具体 class

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

我正在使用 Spring Boot 和 Spring Boot JPA 编写一个组件。我有这样的设置:

接口:

public interface Something {
    // method definitions
}

实施:

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

现在,我有一个使用 SpringJUnit4ClassRunner 运行的 JUnit 测试,我想用它来测试我的 SomethingImpl

当我做的时候

@Autowired
private Something _something;

它有效,但是

@Autowired
private SomethingImpl _something;

导致测试失败并抛出 NoSuchBeanDefinitionException 消息 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)}

但是在测试用例中,我想明确地注入我的SomethingImpl,因为它是我要测试的class。我该如何实现?

如果你想要一个特殊的 bean,你必须使用 @Qualifier 注释:

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

我发现你可以用 javax.inject 风格的 DI 做同样的事情:

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

你想注入的地方:

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

这已被 @EnableAutoConfiguration@ComponentScan 正确拾取。

我认为你需要在实现 class 时添加 @Service .. 比如

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

我有同样的问题,我可以通过向应用程序添加组件扫描路径来解决问题 class 如下:

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