Spring Boot:在自动装配具体类时没有“找到类型的限定bean”

时间:2015-03-06 08:55:12

标签: java spring hibernate spring-mvc spring-boot

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

4 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:4)

我发现你可以用javax.inject风格的DI:

做同样的事情
@Named("myConcreteThing")
public class SomethingImpl implements Something { ... }

你要注射的地方:

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

@EnableAutoConfiguration@ComponentScan正确选择了这一点。

答案 2 :(得分:2)

我认为您需要在实现类中添加@Service ..比如

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

答案 3 :(得分:1)

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

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