我创建了一个自定义的春天@Qualifier
注解:
@Target({
ElementType.FIELD,
ElementType.METHOD,
ElementType.PARAMETER,
ElementType.TYPE,
ElementType.ANNOTATION_TYPE
})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Database {
String value() default "";
}
然后我applyed此批注各种执行豆类:
@Repository
@Database("mysql")
class MySqlActionRepository implements ActionRepository {}
@Repository
@Database("oracle")
class OracleActionRepository implements ActionRepository {}
@Repository
@Database("sqlserver")
class SqlServerActionRepository implements ActionRepository {}
现在,作为在运行时,只有这些豆类中的一个必须是可用注射,我创建了一个@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
一个时,才有效。
任何想法,我怎么能解决这个问题呢?
似乎从here,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...");
}