基本上我想創建一個具體的bean,如果一個屬性被設置,並且某種類型的NoopBean具有相同的接口但什麼都不做。Spring Boot - 當屬性設置時創建bean,否則創建默認bean
乾淨的方法是什麼?
基本上我想創建一個具體的bean,如果一個屬性被設置,並且某種類型的NoopBean具有相同的接口但什麼都不做。Spring Boot - 當屬性設置時創建bean,否則創建默認bean
乾淨的方法是什麼?
您可以將對象描述爲bean,其創建取決於您的自定義條件。該配置可以是這樣的:
@Configuration
public class YourConfiguration {
@Bean(name="concreteBean")
@Conditional(YourCondition.class)
public YourInterface concreteBean(){
return new ConcreteBean();
}
@Bean(name="noopBean")
@Conditional(YourCondition.class)
public YourInterface noopBean(){
return new NoopBean();
}
}
的@Conditional註釋可以與依賴於部件的掃描處理與@Component
註解的類可替代地使用。
你還需要一類,這將描述的條件,如:
public class YourCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return "concret".equals(context.getEnvironment().getProperty("your.property"));
}
}
具有描述了這種情況是高度靈活的一類,但如果你只是想檢查屬性,你可以使用@Condition
這是@ConditionalOnProperty的更專業版本,並擺脫條件類。在這種情況下,您直接在bean上的註釋中描述條件。
@ConditionalOnProperty(name="your.property", havingValue="concret")
這種情況下的缺點是您需要在每個bean中重複相同的條件。推薦使用帶有單獨類的簡單@Conditional
,因爲它可以獲得適當的有意義的名稱。
一種選擇是:
@Bean
public MyInterface myBean() {
if (somePropertySet) {
return new RealBean();
} else {
return new NoOpBean();
}
}
另一種選擇是使用Spring配置文件。如果你已經使用了春天型材
@Bean
@Profile("noop-profile")
public MyInterface myBean() {
return new NoOpBean();
}
@Bean
@Profile("real-profile")
public MyInterface myBean() {
return new RealBean();
}
第二屆選項可能是有意義的(例如,「生產」,「分期」等)