![](/img/trans.png)
[英]Spring Boot @MockBeans - How to use the same beans in multiple test classes
[英]Multiple beans with the same implementation in Spring boot
我有一種情況,我正在為特定的 bean 使用一種可能的實現,它看起來像這樣:
@Configuration
public class MyConfig {
@Autowired
private ApplicationContext context;
@Bean
public SomeInterface someInterface() {
if (this.context.getEnvironment().getProperty("implementation") != null) {
return new ImplementationOne();
} else {
return new ImplementationTwo();
}
}
}
到目前為止,這很有效,直到出現新的需求,使用一個額外的接口,目前只有ImplementationTwo
提供實現,將它與ImplementationOne
一起使用是沒有意義的:
@Bean
public SomeOtherInterface someOtherInterface() {
return new ImplementationTwo();
}
我想這會起作用,但我想知道這是否真的有意義,因為在一種情況下,我可以讓兩個 bean 基本上實例化同一個對象。 那有意義嗎 ? 有沒有更好的方法來實現同樣的目標?
我相信,如果您有單個接口的多個實現,那么您應該使用特定的 bean 名稱,如下所示。
這里 implementation1 將是在我們擁有 Interface1 依賴項的任何地方創建和注入的主要 bean。
@Primary
@Bean
public Interface1 implementation1() {
return new Implementation2();
}
@Bean
public Interface1 implementation2() {
return new Implementation2();
}
如果我們需要注入 implementation2,我們需要 @Resource 注釋,如下所示。
@Resource(name="implementation2")
Interface1 implementation2;
您始終可以在使用特定 bean 的每個地方定義一個限定符:
@Bean
public SomeInterface beanName1(){ //impl }
@Bean
public SomeInterface beanName2(){ //impl }
用法:
@Qualifier("beanName1") SomeInterface interface;
還需要在application.yml/properties
文件中允許多個 bean:
spring.main.allow-bean-definition-overriding=true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.