SpringBoot 如何從配置文件讀取值到對(duì)象中
一、實(shí)現(xiàn)方式
@ConfigurationProperties 注解
(最好加上前綴prefix=“person”,標(biāo)明是和配置文件中哪個(gè)開頭的屬性匹配)
推薦使用用在類上,從配置文件讀取屬性值,放到對(duì)象里面,復(fù)雜的結(jié)構(gòu)也適用例如map,list,對(duì)象。支持校驗(yàn):@Validated
@Valid注解
用在屬性上,需要每個(gè)屬性逐個(gè)綁定通過(guò)@value注解獲取配置文件的值,不適合做復(fù)雜類型(map,list ,對(duì)象)值得獲取不支持@Validated
二、兩者區(qū)別

三、代碼演示
使用@ConfigurationProperties注解
package com.wx.springboot20190911.demo.model;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.Email;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 1.ConfigurationProperties注解 從配置文件讀取屬性值,放到對(duì)象里面
* 2.通過(guò)@value注解獲取配置文件的值
*/
@Component//perosn 需要納入spring ioc 容器里
@ConfigurationProperties(prefix = "person")//使用前綴標(biāo)明具體的屬性
@Validated
public class Person {
@Email
String email;
String hello;
String name;
int age;
boolean boss;
Date birth;
Map<String,String> maps;
List<String> list;
Dog dog;
@Override
public String toString() {
return "Person{" +
"email='" + email + '\'' +
", hello='" + hello + '\'' +
", name='" + name + '\'' +
", age=" + age +
", boss=" + boss +
", birth=" + birth +
", maps=" + maps +
", list=" + list +
", dog=" + dog +
'}';
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isBoss() {
return boss;
}
public void setBoss(boolean boss) {
this.boss = boss;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Map<String, String> getMaps() {
return maps;
}
public void setMaps(Map<String, String> maps) {
this.maps = maps;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
}
package com.wx.springboot20190911.demo.model;
public class Dog {
String name;
String color;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", color='" + color + '\'' +
", age=" + age +
'}';
}
}
使用@Value注解
package com.wx.springboot20190911.demo.model;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.Email;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 1.ConfigurationProperties注解 從配置文件讀取屬性值,放到對(duì)象里面,推薦使用,復(fù)雜的結(jié)構(gòu)也適用例如map,list對(duì)象,
* 支持 校驗(yàn)@Validated
* 2.通過(guò)@value注解獲取配置文件的值,不適合做復(fù)雜類型值得獲取,不支持@Validated,支持
*/
@Component//perosn 需要納入spring ioc 容器里
//@ConfigurationProperties(prefix = "person")
@Validated
public class Person1 {
@Email
@Value("${person1.email}")
String email;
@Value("${person1.hello}")
String hello;
@Value("${person1.name}")
String name;
@Value("#{12*3}")//支持計(jì)算
int age;
@Value("${person1.boss}")
boolean boss;
@Value("${person1.birth}")
Date birth;
Map<String,String> maps;
List<String> list;
Dog dog;
public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isBoss() {
return boss;
}
public void setBoss(boolean boss) {
this.boss = boss;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Map<String, String> getMaps() {
return maps;
}
public void setMaps(Map<String, String> maps) {
this.maps = maps;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Person1{" +
"email='" + email + '\'' +
", hello='" + hello + '\'' +
", name='" + name + '\'' +
", age=" + age +
", boss=" + boss +
", birth=" + birth +
", maps=" + maps +
", list=" + list +
", dog=" + dog +
'}';
}
}
配置類(application.properties)代碼
person.hello=luck person.name=吳 #亂碼的話 就setting設(shè)置下file encoding person.list=ww,xx,rr person.maps.k1=v1 person.maps.k2=v2 person.dog.name=cat person.dog.color=red person.dog.age=1 person.age=12 person.birth=2019/01/11 person.boss=false person.email=www@qq.com person1.hello=luck person1.name=吳 #亂碼的話 就setting設(shè)置下file encoding person1.list=ww,xx,rr person1.age=12 person1.birth=2019/01/11 person1.boss=false person1.email=www
配置類(application.yml)代碼:這種方式更加結(jié)構(gòu)化
person:
name: 霞
age: 16
boss : false
birth: 2012/09/12
maps: {k1: v1,k2: v2}
list: [dog,cat ,house,rabbits]
dog:
name: ${person.hello}
age: ${random.int(10)}
color: white
hello: yula
打印結(jié)果:使用第一種方式時(shí),如果email不是"www@qq.com"這種格式,是不能運(yùn)行成功的,但是使用@Value 不會(huì)校驗(yàn),如下面是"www",一樣能運(yùn)行成功
Person{email='www@qq.com', hello='luck', name='吳', age=12, boss=false, birth=Fri Jan 11 00:00:00 CST 2019, maps={k1=v1, k2=v2}, list=[ww, xx, rr], dog=Dog{name='cat', color='red', age=1}}
Person1{email='www', hello='luck', name='吳', age=36, boss=false, birth=Fri Jan 11 00:00:00 CST 2019, maps=null, list=null, dog=null}
四、@PropertySource 讀取指定配置文件
package com.wx.springboot20190911.demo.model;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.Email;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 1.ConfigurationProperties注解 從配置文件讀取屬性值,放到對(duì)象里面
* 2.通過(guò)@value注解獲取配置文件的值
*/
@PropertySource(value={"classpath:person.properties"})//指定讀取person.properties配置文件
@Component//perosn 需要納入spring ioc 容器里
@ConfigurationProperties(prefix = "person")//使用前綴標(biāo)明具體的屬性
@Validated
public class Person2 {
@Email
String email;
String hello;
String name;
int age;
boolean boss;
Date birth;
Map<String,String> maps;
List<String> list;
Dog dog;
@Override
public String toString() {
return "Person{" +
"email='" + email + '\'' +
", hello='" + hello + '\'' +
", name='" + name + '\'' +
", age=" + age +
", boss=" + boss +
", birth=" + birth +
", maps=" + maps +
", list=" + list +
", dog=" + dog +
'}';
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isBoss() {
return boss;
}
public void setBoss(boolean boss) {
this.boss = boss;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Map<String, String> getMaps() {
return maps;
}
public void setMaps(Map<String, String> maps) {
this.maps = maps;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
}
這里雖然指定了讀取person.properties配置文件,但是由于prefix=“person”,導(dǎo)致還是讀取了application.properties配置文件,因?yàn)閍pplication.properties權(quán)限最高,要想讀取person.properties配置文件,就得改前綴名,例如改成prefix=“person2” person.properties配置文件的內(nèi)容如下:

沒(méi)改前綴名的結(jié)果演示:
Person{email='www@qq.com', hello='luck', name='吳', age=12, boss=false, birth=Fri Jan 11 00:00:00 CST 2019, maps={k1=v1, k2=v2}, list=[ww, xx, rr], dog=Dog{name='cat', color='red', age=1}}
Person1{email='www', hello='luck', name='吳', age=36, boss=false, birth=Fri Jan 11 00:00:00 CST 2019, maps=null, list=null, dog=null}
Person{email='www@qq.com', hello='luck', name='吳', age=12, boss=false, birth=Fri Jan 11 00:00:00 CST 2019, maps={k1=v1, k2=v2}, list=[ww, xx, rr], dog=Dog{name='cat', color='red', age=1}}
改前綴名的代碼演示:

改了前綴名的結(jié)果演示:這時(shí)候讀取的就是指定的配置文件的值
Person{email='www@qq.com', hello='luck', name='吳', age=12, boss=false, birth=Fri Jan 11 00:00:00 CST 2019, maps={k1=v1, k2=v2}, list=[ww, xx, rr], dog=Dog{name='cat', color='red', age=1}}
Person1{email='www', hello='luck', name='吳', age=36, boss=false, birth=Fri Jan 11 00:00:00 CST 2019, maps=null, list=null, dog=null}
Person{email='12345@qq.com', hello='springboot', name='指定讀取配置文件', age=12, boss=false, birth=Wed Sep 11 00:00:00 CST 2019, maps={k2=v2, k1=v1}, list=[@Value, @PropertySource], dog=Dog{name='cat', color='red', age=1}}
注:只能讀取 .properties 文件,無(wú)法讀取 .yml 文件
五、@ImportResource:導(dǎo)入Spring配置文件
讓配置文件里面的內(nèi)容生效
Springboot 里沒(méi)有Spring 的配置文件,我們自己編寫的配置文件,也不能自動(dòng)識(shí)別;
想讓Spring的配置文件生效,加載進(jìn)來(lái),需使用該注解
寫一個(gè)Person3 類,如圖所示:

自定義一個(gè)Spring配置文件,如圖所示:

在啟動(dòng)類上注解

測(cè)試:自定義的這個(gè)配置文件是否生效

演示結(jié)果:生效了
2019-09-11 22:15:12.247 INFO 7824 --- [ main] c.w.s.demo.DemoApplicationTests : Started DemoApplicationTests in 8.558 seconds (JVM running for 10.882)
Person{email='null', hello='null', name='null', age=0, boss=false, birth=null, maps=null, list=null, dog=null}
六、思維導(dǎo)圖

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java調(diào)用JavaScript實(shí)現(xiàn)字符串計(jì)算器代碼示例
這篇文章主要介紹了Java調(diào)用JavaScript實(shí)現(xiàn)字符串計(jì)算器代碼示例,具有一定參考價(jià)值,需要的朋友可以了解下。2017-12-12
java實(shí)現(xiàn)隊(duì)列queue數(shù)據(jù)結(jié)構(gòu)詳解
大家好,本篇文章主要講的是java實(shí)現(xiàn)隊(duì)列queue數(shù)據(jù)結(jié)構(gòu)詳解,感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下2022-02-02
Java基于Socket實(shí)現(xiàn)簡(jiǎn)單的多線程回顯服務(wù)器功能示例
這篇文章主要介紹了Java基于Socket實(shí)現(xiàn)簡(jiǎn)單的多線程回顯服務(wù)器功能,結(jié)合實(shí)例形式分析了java使用socket進(jìn)行多線程數(shù)據(jù)傳輸?shù)南嚓P(guān)操作技巧,需要的朋友可以參考下2017-08-08
如何解決IDEA使用Tomcat控制臺(tái)中文出現(xiàn)亂碼問(wèn)題
這篇文章主要介紹了如何解決IDEA使用Tomcat控制臺(tái)中文出現(xiàn)亂碼問(wèn)題,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09
關(guān)于java.lang.NumberFormatException: null的問(wèn)題及解決
這篇文章主要介紹了關(guān)于java.lang.NumberFormatException: null的問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09
Java多線程之synchronized關(guān)鍵字的使用
這篇文章主要介紹了Java多線程之synchronized關(guān)鍵字的使用,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)java的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-04-04
SpringBoot讀取yml文件中配置數(shù)組的2種方法
這篇文章主要介紹了SpringBoot讀取yml文件中配置數(shù)組的2種方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12
Java數(shù)據(jù)結(jié)構(gòu)與算法之循環(huán)隊(duì)列的實(shí)現(xiàn)
循環(huán)隊(duì)列 (Circular Queue) 是一種特殊的隊(duì)列。循環(huán)隊(duì)列解決了隊(duì)列出隊(duì)時(shí)需要將所有數(shù)據(jù)前移一位的問(wèn)題。本文將帶大家詳細(xì)了解循環(huán)隊(duì)列如何實(shí)現(xiàn),需要的朋友可以參考一下2021-12-12
Jmeter參數(shù)化實(shí)現(xiàn)原理及過(guò)程解析
這篇文章主要介紹了Jmeter參數(shù)化實(shí)現(xiàn)原理及過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07

