![](/img/trans.png)
[英]How to use bean arraylist into the another bean with hibernate annotation?
[英]How use an annotation's value to initialize a bean
我有以下注釋。
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Import(MyBeanInitializer.class)
public @interface MyAnnotation {
String clientType() default "" ;
}
我有一個 Bean 初始化組件,如下所示
@Configuration
public class MyBeanInitializer {
@Bean() // trigger this when annoattion's value == "A"
public CommonBean firstBean() {
return new BeanA;
}
@Bean() // trigger this when annoattion's value == "B"
public CommonBean firstBean() {
return new BeanB;
}
}
BeanA 和 BeanB 的我的 Common 接口
public interface CommonBean {
void doSomething();
}
我的兩個實現是
@Component()
public class BeanA implements CommonBean {
@Overrid
public void doSomething (){
// implementation here
}
}
@Component()
public class BeanB implements CommonBean {
@Overrid
public void doSomething (){
// implementation here
}
}
我需要將上面用作另一個 Spring 引導項目的庫。 在該項目中,我使用@MyAnnotation(clientType="web")
注釋Application.java
,然后使用構造函數注入將BeanA或BeanB注入該項目內的 class。
通過查看通過注釋傳遞的值來初始化 bean 的機制是什么?
不要為此使用注釋值。
注釋值在編譯時是硬編碼的,不能動態更改。 另外,面對@Conditional
,它看起來和感覺都非常尷尬,它已經存在並與獲取動態屬性的能力相關聯。
您想要做的是使用@Conditional
的組合,它允許您在給定特定環境變量的情況下定義要執行的操作,或者使用Spring Boot中的@ConditionalOnProperty
注釋來簡單地提供基於 bean 的連接能力在特定屬性中存在特定值。
這就是它的樣子。 假設您有名為common.basicImpl
和common.advancedImpl
的屬性。
@Component
@ConditionalOnProperty(prefix = "common", value = "basicImpl")
public class BeanA implements CommonBean {
@Override
public void doSomething (){
// implementation here
}
}
@Component
@ConditionalOnProperty(prefix = "common", value = "advancedImpl")
public class BeanB implements CommonBean {
@Override
public void doSomething (){
// implementation here
}
}
請注意,僅此一項並不能解決兩個屬性都存在的情況,並且您不能執行多個@ConditionalOnProperty
語句。 添加@ConditionalOnMissingBean
以確保您不會意外地將它們同時連接起來會對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.