1. 程式人生 > 實用技巧 >SpringBoot中SpEL表示式讀取配置檔案的屬性

SpringBoot中SpEL表示式讀取配置檔案的屬性

Spring Expression Language (SpEL)是一種功能非常強大的表示式語言,可用於在執行時查詢和操作物件。 SpEL書寫在XML配置檔案或者Annotation註解上,在Spring Bean的建立過程中生效。

SpEL能用在很多的場景下,在這篇文章中,給大家介紹一下在Spring Boot中如何使用SpEL表示式讀取配置屬性。

一、使用SpEL表示式繫結字串集合

建立一個配置檔案SpELread.properties,內容如下:

employee.names=james,curry,zimug,姚明
employee.type=教練,球員,經理
employee.age={one:'27', two : '35', three : '34', four: '26'}
  • 上文中names和type屬性分別代表僱員employee的名字和分類,是字串型別屬性
  • age屬性代表僱員的年齡,是一組鍵值對、類物件資料結構

建立一個配置類 Employee ,程式碼如下:

@Data
@Configuration
@PropertySource (name = "employeeProperties",
        value = "classpath:employee.properties",
        encoding = "utf-8")
public class Employee {

    //使用SpEL讀取employee.properties配置檔案
    @Value("#{'${employee.names}'.split(',')}")
    private List<String> employeeNames;

}
  • @Value註解和@PropertySource註解參考《YAML配置繫結變數的兩種方式》和《載入舊專案配置檔案的兩種方式》學習

二、測試用例

Employee類中

/**
 * 通過SpEL表示式讀取配置檔案當中的值
 */
@Data
@Component
//@Configuration
// 防止亂碼加上encoding屬性,value屬性指定配置檔案的位置,name屬性定義別名。此註解作用載入配置檔案
@PropertySource(name = "employeeProperties", value = "classpath:SpELread.properties", encoding = "utf-8")
public class Employee {

    //使用SpEL讀取employee.properties配置檔案

    //獲取employee的所有名字(因為配置檔案中用的都是|分隔的)。用雙斜槓轉譯一下\\變成逗號,隔開。
    @Value("#{'${employee.names}'.split('\\|')}")
    private List<String> employeeNames;

    //獲取employee的第一個名字
    @Value ("#{'${employee.names}'.split('\\|')[0]}")
    private String firstEmployeeName;   //

    //獲取employee年齡鍵值對的集合。
    @Value ("#{${employee.age}}")
    private Map<String, Integer> employeeAge;

    //獲取employee年齡鍵值對的集合中第二個的年齡值。
    @Value ("#{${employee.age}.two}")
    //@Value ("#{${employee.age}['two']}")  //這樣寫也可以
    private String employeeAgeTwo;

    //獲取employee年齡鍵值對的集合中第五個的年齡值(集合中沒有第five個的元素!),設定預設值。
    @Value ("#{${employee.age}['five'] ?: 31}")
    private Integer ageWithDefaultValue;

    //SpEL結合 @Value註解讀取系統環境變數
    @Value ("#{systemProperties['java.home']}")
    private String javaHome;

    //SpEL結合 @Value註解獲取系統使用者工作目錄
    @Value ("#{systemProperties['user.dir']}")
    private String userDir;

    //輸出:Employee(employeeNames=[james, curry, zimug, 姚明], firstEmployeeName=james, employeeAge={one=27, two=35, three=34, four=26}, employeeAgeTwo=35, ageWithDefaultValue=31, javaHome=C:\develop\Java\jdk1.8.0_91\jre, userDir=C:\Users\asus\IdeaProjects\Microservice\SpringBoot-yml)
}

測試方法

@SpringBootTest
class SpringbootYmlApplicationTests {
    /**
     * 測試通過SpEL表示式讀取配置檔案當中的值
     */
    @Test
    public void test3(){
        System.out.println(employee.toString());
    }
}

當然,除了以上在Spring Boot中使用SpEL的常用用法,SpEL還可以完成算術運算、邏輯運算、正則匹配運算、條件運算等功能。建議大家參照官方文件學習。更多內容可以參考:https://docs.spring.io/spring/docs/4.3.10.RELEASE/spring-framework-reference/html/expressions.html

三、讀取properties檔案中文亂碼問題的解決

File->settings->File Encoding->圖所示選項及勾選

使用PropertySource註解時指定encoding

// 防止亂碼加上encoding屬性,value屬性指定配置檔案的位置,name屬性定義別名。此註解作用載入配置檔案
@PropertySource(name = "employeeProperties", value = "classpath:SpELread.properties", encoding = "utf-8")