本文主要介紹Spring @Value 注解注入屬性值的使用方法的分析,文章通過示例代碼非常詳細地介紹,對于每個人的學習或作業都有一定的參考學習價值
在使用spring框架的專案中,@Value是經常使用的注解之一,其功能是將與組態檔中的鍵對應的值分配給其帶注解的屬性,在日常使用中,我們常用的功能相對簡單,本文使您系統地了解@Value的用法,
@Value注入形式
根據注入的內容來源,@ Value屬性注入功能可以分為兩種:通過組態檔進行屬性注入和通過非組態檔進行屬性注入,
非組態檔注入的型別如下:
- 注入普通字串
- 注入作業系統屬性
- 注射表達結果
- 注入其他bean屬性
- 注入檔案資源
- 注入URL資源
基于組態檔的注入
首先,讓我們看一下組態檔中的資料注入,無論它是默認加載的application.properties還是自定義my.properties檔案(需要@PropertySource額外加載),例如:application.properties屬性值以以下形式定義:
user.name=admin
my.properties組態檔中定義的屬性如下:
user.password=pwd123
然后,在bean中使用@Value,如下所示:
@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
可以通過以下方式注入它:
/**
*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;
上面的示例顯示了以下方案的使用:
- 直接注入字串等效于實體化時直接初始化字串,初始化空串
- 通過#{}注入系統變數,
- 運算式計算結果通過#{}注入,
- 通過#{}注入其他bean的屬性,
- 通過{}和$ {}的組合注入屬性,然后拆分,
- 注入檔案資源,并將相應的字串值轉換為相應的資源檔案,
- 注入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;
$ {}中直接使用“:”來設定未定義或空值的默認值,而#{}則需要使用“?:”來設定未設定屬性的默認值,
歡迎關注我的博客,里面有很多精品合集
- 本文轉載注明出處(必須帶連接,不能只轉文字):字母哥博客,
覺得對您有幫助的話,幫我點贊、分享!您的支持是我不竭的創作動力! ,另外,筆者最近一段時間輸出了如下的精品內容,期待您的關注,
- 《手摸手教你學Spring Boot2.0》
- 《Spring Security-JWT-OAuth2一本通》
- 《實戰前后端分離RBAC權限管理系統》
- 《實戰SpringCloud微服務從青銅到王者》
- 《VUE深入淺出系列》
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/147629.html
標籤:Java
