1. 程式人生 > 其它 >從配置檔案中獲取list,set,map值

從配置檔案中獲取list,set,map值

1,解析List:

testList:
  list: aaa,bbb,ccc

@Value("#{'${testList.list}'.split(',')}")
private List<String> testList;
//加上預設值(多了一個 : 號,冒號後的值表示當 key 不存在時候使用的預設值,使用預設值時陣列的 length = 0。),避免不配置這個 key 時候程式報錯:
@Value("#{'${testList.list:}'.split(',')}")
private List<String> testList;
//但是這樣有個問題,當不配置該 key 值,預設值會為空串,它的 length = 1(不同於陣列,length = 0),這樣解析出來 list 的元素個數就不是空了。
//這個問題比較嚴重,因為它會導致程式碼中的判空邏輯執行錯誤。這個問題也是可以解決的,在 split() 之前判斷下是否為空即可。
@Value("#{'${testList.list:}'.empty ? null : '${testList.list:}'.split(',')}")
private List<String> testList;

2,解析Set

testSet:
set: 111,222,333,111

@Value("#{'${testSet.set:}'.empty ? null : '${testSet.set:}'.split(',')}")
private Set<Integer> testSet;

3,解析Map

testMap:
  map1: '{"name": "zhangsan", "sex": "male"}'
  map2: '{"math": "90", "english": "85"}'
@Value("#{${test.map1}}")
private Map<String,String> map1;

@Value(
"#{${test.map2}}") private Map<String,Integer> map2;

注意,使用這種方式,必須得在配置檔案中配置該 key 及其 value。我在網上找了許多資料,都沒找到利用 EL 表示式支援不配置 key/value 的寫法。

如果你真的很需要這個功能,就得自己寫解析方法了

(1) 自定義解析方法

public class MapDecoder {
    public static Map<String, String> decodeMap(String value) {
        try {
            return
JSONObject.parseObject(value, new TypeReference<Map<String, String>>(){}); } catch (Exception e) { return null; } } }

(2) 在程式中指定解析方法

@Value("#{T(com.github.jitwxs.demo.MapDecoder).decodeMap('${test.map1:}')}")
private Map<String, String> map1;

@Value("#{T(com.github.jitwxs.demo.MapDecoder).decodeMap('${test.map2:}')}")
private Map<String, String> map2;

特別注意的是@Value註解不能和@AllArgsConstructor註解同時使用,否則會報錯

轉自:https://jitwxs.cn/d6d760c4.html