亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Spring - 在運行時使用自定義限定符獲取 bean

Spring - 在運行時使用自定義限定符獲取 bean

慕田峪9158850 2022-06-04 16:29:58
我創建了一個自定義 Spring@Qualifier注釋:@Target({        ElementType.FIELD,        ElementType.METHOD,        ElementType.PARAMETER,         ElementType.TYPE,        ElementType.ANNOTATION_TYPE})@Retention(RetentionPolicy.RUNTIME)@Qualifierpublic @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 中的一個必須可用于注入,我創建了一個@PrimaryBean 方法。@Bean@PrimaryActionRepository actionRepository(        final ApplicationContext applicationContext,        final Configuration configuration) {    final var database = configuration.getString("...");    return BeanFactoryAnnotationUtils.qualifiedBeanOfType(            applicationContext,            ActionRepository.class,            database    );}但是,此解決方案不適用于我的自定義注釋。它僅在使用標準時有效@Qualifier。知道如何解決這個問題嗎?
查看完整描述

1 回答

?
長風秋雁

TA貢獻1757條經驗 獲得超7個贊

從這里看來,BeanFactoryAnnotationUtils不支持你的情況。但是我們可以結合 ApplicationContext'sgetBeansOfType()和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...");

}


查看完整回答
反對 回復 2022-06-04
  • 1 回答
  • 0 關注
  • 162 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號