春天 - 在运行时获得豆与自定义的限定

问题描述 投票:2回答:1

我创建了一个自定义的春天@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一个时,才有效。

任何想法,我怎么能解决这个问题呢?

java spring
1个回答
1
投票

似乎从hereBeanFactoryAnnotationUtils不支持你的情况。但是,我们可以结合ApplicationContextgetBeansOfType()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...");
}
© www.soinside.com 2019 - 2024. All rights reserved.