結合SpEL使用@Value-基於配置文件或非配置的文件的值注入-Spring Boot

本文主要介紹Spring @Value 註解注入屬性值的使用方法的分析,文章經過示例代碼很是詳細地介紹,對於每一個人的學習或工做都有必定的參考學習價值vue

在使用spring框架的項目中,@Value是常常使用的註解之一。其功能是將與配置文件中的鍵對應的值分配給其帶註解的屬性。在平常使用中,咱們經常使用的功能相對簡單。本文使您系統地瞭解@Value的用法。java

@Value注入形式

根據注入的內容來源,@ Value屬性注入功能能夠分爲兩種:經過配置文件進行屬性注入和經過非配置文件進行屬性注入。spring

非配置文件注入的類型以下:後端

  • 注入普通字符串
  • 注入操做系統屬性
  • 注射表達結果
  • 注入其餘bean屬性
  • 注入文件資源
  • 注入URL資源

基於配置文件的注入

首先,讓咱們看一下配置文件中的數據注入,不管它是默認加載的application.properties仍是自定義my.properties文檔(須要@PropertySource額外加載)。例如:application.properties屬性值以如下形式定義:數組

user.name=admin

my.properties配置文件中定義的屬性以下:springboot

user.password=pwd123

而後,在bean中使用@Value,以下所示:app

@PropertySource("classpath:my.properties")
@RestController
public class ValueController {

  /**
   *Get in application.properties Properties configured in
   */
  @Value("${user.name}")
  private String name;

  /**
   *Get in my.properties Configuration properties in
   */
  @Value("${user.password}")
  private String password;

}

區別在於,在spring boot項目中,若是使用my.properties文件,則須要經過類中的@ PropertySource導入配置文件,而application.properties中的屬性將自動加載。框架

同時,您不只能夠經過@Value注入單個屬性,還能夠採用數組和列表的形式。例如,配置以下:前後端分離

tools=car,train,airplane

能夠經過如下方式注入它:dom

/**
 *Injection array (automatically split according to ",")
 */
@Value("${tools}")
private String[] toolArray;

/**
 *Injection list form (automatic segmentation based on "," and)
 */
@Value("${tools}")
private List<String> toolList;

默認狀況下,spring將以「,」分割,並將其轉換爲相應的數組或列表。

基於非配置文件的注入

在使用示例說明基於非配置文件注入屬性的實例以前,讓咱們看一下SpEl。

Spring Expression Language是Spring表達式語言,能夠在運行時查詢和操做數據。使用#{…}做爲操做符號,大括號中的全部字符均視爲SpEl。

讓咱們看一下特定實例場景的應用:

/**
 *實例化一個字符串,並賦予默認值
 */
@Value
private String wechatSubscription;

/**
 *讀取系統的環境變量
 */
@Value("#{systemProperties['os.name']}")
private String systemPropertiesName;

/**
 *注入表達式計算結果
 */
@Value("#{ T(java.lang.Math).random() * 100.0 }")
private double randomNumber;

/**
 *讀取一個bean:config的tool屬性並注入
 */
@Value("#{config.tool}")
private String tool;

/**
 *將words用「|」分隔爲字符串數組
 */
@Value("#{'${words}'.split('\|')}")
private List<String> numList;

/**
 *注入一個文件資源
 */
@Value("classpath:config.xml")
private Resource resourceFile;

/**
 *注入 URL 資源
 */
@Value("http://www.choupangxia.com")
private URL homePage;

上面的示例顯示瞭如下方案的使用:

  1. 直接注入字符串等效於實例化時直接初始化字符串。初始化空串
  2. 經過#{}注入系統變量。
  3. 表達式計算結果經過#{}注入。
  4. 經過#{}注入其餘bean的屬性。
  5. 經過{}和$ {}的組合注入屬性,而後拆分。
  6. 注入文件資源,並將相應的字符串值轉換爲相應的資源文件。
  7. 注入URL資源並將相應的URL字符串轉換爲URL。

默認值注入

不管使用#{}(SpEL)仍是$ {}進行屬性注入,當沒法得到相應的值時,都須要設置默認值,能夠經過如下方式進行設置。

/**
 *If IP is not configured in the property, the default value is used
 */
@Value("${ip:127.0.0.1}")
private String ip;

/**
 *If the value of port is not obtained in the system properties, 8888 is used.
 */
@Value("#{systemProperties['port']?:'8888'}")
private String port;

$ {}中直接使用「:」來設置未定義或空值的默認值,而#{}則須要使用「?:」來設置未設置屬性的默認值。

歡迎關注個人博客,裏面有不少精品合集

  • 本文轉載註明出處(必須帶鏈接,不能只轉文字):字母哥博客

以爲對您有幫助的話,幫我點贊、分享!您的支持是我不竭的創做動力! 。另外,筆者最近一段時間輸出了以下的精品內容,期待您的關注。

相關文章
相關標籤/搜索