SpringBoot複雑構成情報読み出し

2564 ワード

前言


前のブログSpring Bootに続き、プロファイルのカスタム情報を読み込みます.
上記のシーンは、比較的簡単なプロパティファイルに適用されます.しかし、実際の作業では、プロファイルのkeyにも変数情報が含まれている構成が必要です.次のようになります.
tran.subtype. .id=xxx
tran.subtype. .infoTableName=xxx
tran.subtype. .msgTemplate=xxx
tran.subtype. .receiverSASMap. =SAS 

ここでは、複数のトランザクションサブタイプの構成をサポートし、id、infoTable Name、msgTemplateプロパティの値をそれぞれ指定します.さらに、receiverSASMapというmapタイプの構成もあります.このmapは、SASルールエンジンが結果とデータベーステーブルフィールドの対応関係を返すように構成するために使用されます.すなわちpropertiesファイルのkeyには、上図の の2つの変数が存在する.
実際のプロパティ・ファイルは次のとおりです.
tran.subtype.toUser.id=0001
tran.subtype.toUser.infoTableName=Table1
tran.subtype.toUser.receiverSASMap.RETAILER_INFO=1,2
tran.subtype.toUser.receiverSASMap.BRANCH_INFO=2
tran.subtype.toUser.msgTemplate=ABCtoUser

tran.subtype.toPublic.id=0002
tran.subtype.toPublic.infoTableName=Table2
tran.subtype.toPublic.receiverSASMap.RETAILER_INFO=3,4
tran.subtype.toPublic.receiverSASMap.BRANCH_INFO=5
tran.subtype.toPublic.msgTemplate=DEFtoPublic

このような情報を載せられるbeanをどのように作成しますか?

Beanの作成

@Component
@ConfigurationProperties(prefix = "tran")
public class TranConfigBean {
    public static class Type {
        private String id;
        private String infoTableName;
        private String msgTemplate;
        private Map receiverSASMap;

        // Setters and getters ...
    }

    private Map subtype;

    // Setters and getters.
}

ここでは,@ConfigurationProperties修飾beanにおけるmap型メンバ変数の柔軟な運用について説明する必要がある.
複雑な属性マッチングが分かりにくい点は,Mapの変数名,keyとvalueがpropertiesにどのように対応しているかである.valueタイプが単純なmapの場合:
Map demoMap;

対応するプロパティファイルは次のとおりです.
# key1 key2 demoMap key 
prefix.demoMap.key1=value1
prefix.demoMap.key2=value2

ここで、prefix@ConfigurationPropertiesのprefixの値である.
Mapのvalueのタイプが複雑な場合(bean,listまたはmap):
Map demoMap;
// ...

public static class Student {
    private Integer id;
    private String name;
    // setters and getters
}

対応するプロパティファイルは次のとおりです.
# key1 key2 demoMap key 
prefix.demoMap.key1.id=001
prefix.demoMap.key1.name=paul
prefix.demoMap.key2.id=002
prefix.demoMap.key2.name=peter

まとめ


propertiesファイル構成項目のkeyで変数を使用する場合は、対応するbean内でmapを定義する必要があります.プロパティ・ファイルの書き込みルールは次のとおりです.
prefix.mapName.keyN=valueN接頭辞.map名称keyN=valueN