今天給大家分享冷門但是有很實小知識,Spring 配置文件注入list、map、字節流。
list 注入
properties文件
user.id=3242,2323,1
使用spring el表達式
@Value("#{'${user.id}'.split(',')}")
private List<Integer> list;
yaml 文件
在yml配置文件配置數組方式
number:
arrays:
- One
- Two
- Three
@Value("${number.arrays}")
private List list
雖然網上都說,這樣可以注入,我親身實踐過了,肯定是不能的。會拋出 Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'number.arrays' in value "${number.arrays}"
異常。要想注入必須要使用@ConfigurationProperties
@ConfigurationProperties(prefix = "number")
public class AgentController {
private List arrays;
public List getArrays() {
return arrays;
}
public void setArrays(List arrays) {
this.arrays = arrays;
}
@GetMapping("/s")
public List lists(){
return arrays;
}
不是想這麼麻煩,可以像properties文件寫法,使用el表達式即可
number:
arrays: One,Two,Three
@Value("#{'${number.arrays}'.split(',')}")
private List arrays;
注入文件流
@Value("classpath: application.yml")
private Resource resource;
// 佔位符
@Value("${file.name}")
private Resource resource2;
@GetMapping("/s")
public String lists() throws IOException {
return IOUtils.toString(resource.getInputStream(),"UTF-8");
}
從類路徑加載application.yml
文件將文件注入到org.springframework.core.io.Resource
,可以使用getInputStream()方法獲取流。比起使用類加載器獲取路徑再去加載文件的方式,優雅、簡單不少。
Map Key Value 注入
properties
resource.code.mapper={x86:"hostIp"}
@Value("#{${resource.code.mapper}}")
private Map<String, String> mapper;
成功注入
yaml
在yaml文件中,使用@Value
不能注入Map 實例的,要藉助@ConfigurationProperties
才能實現。
@ConfigurationProperties(prefix = "blog")
public class AgentController {
private Map website;
public Map getWebsite() {
return website;
}
public void setWebsite(Map website) {
this.website = website;
}
@GetMapping("/s")
public String lists() throws IOException {
return JsonUtil.toJsonString(website);
}
配置文件
blog:
website:
juejin: https://juejin.im
jianshu: https://jianshu.com
sifou: https://segmentfault.com/
可以看出@ConfigurationProperties
注入功能遠比@Value
強,不僅能注入List、Map這些,還能注入對象屬性,靜態內部類屬性,這個在Spring Boot Redis模塊 org.springframework.boot.autoconfigure.data.redis.RedisProperties
體現出來。
區別
區別 | @ConfigurationProperties | @Value |
---|---|---|
類型 | 各種複製類型屬性Map、內部類 | 只支持簡單屬性 |
spEl表達式 | 不支持 | 支持 |
JSR303數據校驗 | 支持 | 不支持 |
功能 | 一個列屬性批量注入 | 單屬性注入 |