1. 程式人生 > 其它 >SpringBoot中 @Value 靜態注入 application.yml 中的變數

SpringBoot中 @Value 靜態注入 application.yml 中的變數

技術標籤:springboot

application.yml變數列表

dictionary:
  category: CATEGORY_CODE
  dataTypeList:
    - name: 字串
      code: STRING
    - name: VARCHAR
      code: VARCHAR
      parentCode: STRING
    - name: CHAR
      code: CHAR
      parentCode: STRING
    - name: BPCHAR
      code: BPCHAR
      parentCode: STRING
    - name: TEXT
      code: TEXT
      parentCode: STRING
    - name: MEDIUMTEXT
      code: MEDIUMTEXT
      parentCode: STRING

對映物件配置(核心)

要點:重寫get、set方法;

  1. set方法(無需static修飾)設定靜態變數;
  2. get方法(必須static修飾)
//java專案 www.fhadmin.org
@Configuration
@ConfigurationProperties(prefix = "dictionary")
public class Dictionary{

    @Value("dictionary.category")
    private static String category;
    
    @Value("dictionary.dataTypeList")
    private static List<DataType> dataTypeList;

    public void setCategory(String formCategory) {
        Dictionary.formCategory = formCategory;
    }

    public static String getFormCategory() {
        return formCategory;
    }

    public void setDataTypeList(List<DataType> dataTypeList) {
        Dictionary.dataTypeList = dataTypeList;
    }

    public static List<DataType> getDataTypeList() {
        return dataTypeList;
    }

}
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==