基于Spring boot @Value 注解注入屬性值的操作方法
本文主要介紹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')@RestControllerpublic 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。
讓我們看一下特定實例場景的應用:
/** *實例化一個字符串,并賦予默認值 */@Valueprivate 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;
$ {}中直接使用“:”來設置未定義或空值的默認值,而#{}則需要使用“?:”來設置未設置屬性的默認值。
總結
到此這篇關于結合SpEL使用@Value-基于配置文件或非配置的文件的值注入-Spring Boot的文章就介紹到這了,更多相關Spring @Value 注解注入屬性值內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: