[英]Spring - getting bean at runtime with custom qualifier
我創建了一個自定義 Spring @Qualifier
注釋:
@Target({
ElementType.FIELD,
ElementType.METHOD,
ElementType.PARAMETER,
ElementType.TYPE,
ElementType.ANNOTATION_TYPE
})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Database {
String value() default "";
}
然后我將此注釋應用於各種實現 Bean:
@Repository
@Database("mysql")
class MySqlActionRepository implements ActionRepository {}
@Repository
@Database("oracle")
class OracleActionRepository implements ActionRepository {}
@Repository
@Database("sqlserver")
class SqlServerActionRepository implements ActionRepository {}
現在,在運行時,這些 Bean 中只有一個必須可用於注入,我創建了一個@Primary
Bean 方法。
@Bean
@Primary
ActionRepository actionRepository(
final ApplicationContext applicationContext,
final Configuration configuration) {
final var database = configuration.getString("...");
return BeanFactoryAnnotationUtils.qualifiedBeanOfType(
applicationContext,
ActionRepository.class,
database
);
}
但是,此解決方案不適用於我的自定義注釋。 它僅在使用標准@Qualifier
。
知道我如何解決這個問題嗎?
從這里看來, BeanFactoryAnnotationUtils
不支持您的情況。 但是我們可以結合ApplicationContext
的getBeansOfType()
和findAnnotationOnBean()
來達到同樣的目的:
@Bean
@Primary
ActionRepository actionRepository(final ApplicationContext applicationContext,
final Configuration configuration) {
final var database = configuration.getString("...");
Map<String, ActionRepository> beanMap = context.getBeansOfType(ActionRepository.class);
for (Map.Entry<String, ActionRepository> entry : beanMap.entrySet()) {
Database db = context.findAnnotationOnBean(entry.getKey(), Database.class);
if (db != null && db.value().equals(database)) {
return entry.getValue();
}
}
throw new RuntimeException("Cannot find the bean...");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.