Spring @Value註解 and Spring Boot @ConfigurationProperties註解,
一、Spring的@Value
Spring EL運算式語言,支援在XML和註解中運算式,類是於JSP的EL運算式語言。
在Spring開發中經常涉及調用各種資源的情況,包含普通檔案、網址、設定檔、系統內容變數等,我們可以使用Spring的運算式語言實現資源的注入。
Spring主要在註解@Value的參數中使用運算式。
- 注入一般字元串
- 注入作業系統屬性
- 注入運算式運算結果
- 注入其他Bean的屬性
- 注入檔案內容
- 注入網址內容
- 注入屬性檔案(注意:用的是$符號)
import org.springframework.core.io.Resource;import org.springframework.core.env.Environment;import org.apache.commons.io.IOUtils;@Componentpublic class ELConfig { @Value("注入一般字元串")// 注入一般字元串 private String normal; @Value("#{systemProperties['os.name']}")// 注入作業系統屬性 private String osName; @Value("#{T(java.lang.Math).random() * 100.0 }")// 注入運算式結果 private double randomNumber; @Value("#{payOrderQueryController.payCenterFacade}")// 注入其他Bean屬性 private IPayCenterFacade fromAnother; @Value("classpath:test.txt")// 注入檔案資源 private Resource testFile; @Value("https://www.baidu.com")// 注入網址資源 private Resource testUrl; @Value("${book.name}")// 注入設定檔【注意是$符號】 private String bookName; @Autowired// Properties可以從Environment獲得 private Environment environment; @Override public String toString() { try { return "ELConfig [normal=" + normal + ", osName=" + osName //os.name,如Windows 8.1 + ", randomNumber=" + randomNumber //值如97.53293482705482 + ", fromAnother=" + fromAnother //別的bean的成員屬性 + ", testFile=" + IOUtils.toString(testFile.getInputStream()) //輸出檔案裡的內容 + ", testUrl=" + IOUtils.toString(testUrl.getInputStream()) //輸出網頁的html + ", bookName=" + bookName //配置的值 + ", environment=" + environment.getProperty("book.name") + "]"; } catch (IOException e) { e.printStackTrace(); return null; } } }
二、Spring Boot的@ConfigurationProperties
先看下面的@Value註解:
@Value("${book.name}") private String bookName; @Value("${book.author}") private String bookAuthor;
上面這種使用@Value注入每個配置在實際項目中會顯得格外麻煩,因為我們的配置通常會是許多個,就要使用@Value注入很多次。
Spring Boot提供了基於型別安全的配置方式,通過@ConfigurationProperties將properties屬性和一個Bean關聯,從而實作類別型安全的配置。
@Component@ConfigurationProperties(prefix = "book")public class Book { private String name; private String author; private int age; //get.. set..}
@ConfigurationProperties有兩個屬性
- prefix:指定properties的配置的首碼
- locations:指定properties檔案的位置