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