我正在使用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,因为它是我要测试的类。我该如何实现?

最佳答案

如果您想要特殊的bean,则必须使用@Qualifier批注:

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

08-27 15:46