[英]Oppositely Configured ConditionalOnProperty Beans Autowiring
我有兩個單獨的 bean,配置了兩個自定義條件注釋,它們應該彼此完全相反,並且永遠不會同時自動裝配,但兩者都在自動裝配。 這些注釋將用於許多類,因此我希望能夠在整個應用程序中重用它們,而無需復制 @ConditionalOnProperty 配置。 我的條件是錯誤的,還是有更好的方法在代碼中實現這一點,所以我不必依賴 @Conditional 注釋來選擇自動裝配 bean?
條件注釋:
@Inherited
@Documented
@ConditionalOnProperty(prefix = "my-prefix", value = "enable-this-thing", havingValue = "false", matchIfMissing = false)
public @interface ConditionalOnNotEnablingThisThing {
}
@Inherited
@Documented
@ConditionalOnProperty(prefix = "my-prefix", value = "enable-this-thing", havingValue = "true", matchIfMissing = true)
public @interface ConditionalOnEnablingThisThing {
}
共享界面:
public interface SharedInterface {
void doSomething();
}
實現類:
@Component
@ConditionalOnEnablingThisThing
class EnabledThingComponent implements SharedInterface {
//code
}
@Component
@ConditionalOnNotEnablingThisThing
class NotEnabledThingComponent implements SharedInterface {
//code
}
Class 嘗試自動裝配時拋出多個可用 bean 異常:
@Component
public class MyConsumer {
private final SharedInterface sharedInterface;
public MyConsumer(SharedInterface sharedInterface) {
this.sharedInterface = sharedInterface;
}
//code
}
我想首先說這不是一個理想的解決方案,但它適用於我的特定用例,無需太多繁重的工作。
配置class代碼:
@Configuration(MYCONFIG_NAME_CONSTANT)
public class MyConfig {
private final GenericApplicationContext genericApplicationContext;
public MyConfig(GenericApplicationContext genericApplicationContext) {
this.genericApplicationContext = genericApplicationContext;
configureConditionalBeans();
}
private void configureConditionalBeans() {
if(//my conditional code) {
genericApplicationContext.registerBean(
//registration details for conditional bean
);
}
}
}
需要在這些條件 bean 中自動裝配的組件:
@Component
@DependsOn(MYCONFIG_NAME_CONSTANT) //optional will always be empty without this
public class MyConsumingComponent {
private final Optional<[MyConditionalBean]> conditionalBeanOptional;
public MyConsumingComponent(Optional<[MyConditionalBean]> conditionalBeanOptional) {
this.conditionalBeanOptional = conditionalBeanOptional;
}
//more code here
}
我發現的最大警告是 @ConditionalOnBean 注釋永遠不會找到以這種方式自動裝配的 bean,即使 bean 指定了 @DependsOn 也是如此。 這意味着任何依賴於這些正在配置的底層 bean 的附加條件 bean 都需要以相同的方式有條件地設置。 這給我帶來了很大的痛苦,因為我試圖有條件地自動裝配的 bean 是 Spring 引導庫正在尋找的。 這意味着 Spring 引導依賴 bean 也必須手動配置。 我仍然會對比這更好的解決方案感興趣,但這解決了眼前的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.