SpringBoot は @Autowired を使用して実装クラスを List または Map コレクションに注入します

序文

RuoYi-Vue-Plus最近、翻訳関数Translationの翻訳モジュール設定クラスを見かけましたがTranslationConfig、翻訳インターフェース実装クラスをインジェクションする書き方の一つがTranslationInterfaceとても斬新に感じましたが、この書き方は Spring バージョン 3.0 以降でインジェクションに対応しましListMap。これに気づいたので、この書き方を記録しておきます。

以前のアプローチ

以前は、定義を策略模式+工厂模式結合してSpring上下文的Aware回调取得するのが一般的でしたが、指定类型Bean对象指定した型を取得するBean方法をいくつか紹介します。

  • 方法 1:初期化中にApplicationContextオブジェクトを保存する
  • 方法 2:Spring提供されたクラスを通じてオブジェクトutilsを取得するApplicationContext
  • 方法 3: 抽象クラスから継承するApplicationObjectSupport
  • 方法 4: 抽象クラスから継承するWebApplicationObjectSupport
  • 方法 5: インターフェイスを実装するApplicationContextAware
  • 方法 6:Spring提供されているContextLoader

変換モジュール構成クラス

TranslationConfigここで変換設定が初期化されます

package com.ruoyi.framework.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.TranslationType;
import com.ruoyi.common.translation.TranslationInterface;
import com.ruoyi.common.translation.handler.TranslationBeanSerializerModifier;
import com.ruoyi.common.translation.handler.TranslationHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 翻译模块配置类
 *
 * @author Lion Li
 */
@Slf4j
@Configuration
public class TranslationConfig {
    
    

    @Autowired
    private List<TranslationInterface<?>> list;

    @Autowired
    private ObjectMapper objectMapper;

    @PostConstruct
    public void init() {
    
    
        Map<String, TranslationInterface<?>> map = new HashMap<>(list.size());
        for (TranslationInterface<?> trans : list) {
    
    
            if (trans.getClass().isAnnotationPresent(TranslationType.class)) {
    
    
                TranslationType annotation = trans.getClass().getAnnotation(TranslationType.class);
                map.put(annotation.type(), trans);
            } else {
    
    
                log.warn(trans.getClass().getName() + " 翻译实现类未标注 TranslationType 注解!");
            }
        }
        TranslationHandler.TRANSLATION_MAPPER.putAll(map);
        // 设置 Bean 序列化修改器
        objectMapper.setSerializerFactory(
            objectMapper.getSerializerFactory()
                .withSerializerModifier(new TranslationBeanSerializerModifier()));
    }

}

コレクションがこの構成クラスに挿入されていることがわかりますList。そのタイプはTranslationInterface翻訳インターフェースです

。その実装クラスを見てみましょう。これらの実装クラスはモジュールのパッケージ

の下で定義されています。 、およびの翻訳実装はそれぞれ、変換インターフェースの実装クラスをスキャンします。 に注入されました。効果を見てみましょう。変換インターフェースのすべての実装クラスが実際に挿入されていることがわかります。注釈も挿入できるため、ここではコレクションを手動で追加してデバッグしますブレークポイントを使用すると:commontranslation部门字典OSS用户名

SpringTranslationInterfaceList

DebugTranslationInterface

@AutowiredBeanMapMapDebug

おすすめ

転載: blog.csdn.net/qq_31762741/article/details/132098537