您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“Spring Boot中如何讀取配置”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“Spring Boot中如何讀取配置”這篇文章吧。
本節(jié)我們要解決如下幾個(gè)問題:
如何使用Spring Boot讀取配置文件?有哪些方式?
常用的幾種數(shù)據(jù)結(jié)構(gòu),如字符串、整數(shù)、List、Map,如何配置?如何讀???
如何自定義配置文件的路徑?
Spring Boot默認(rèn)的配置文件有兩種格式: application.properties
和 application.yml
。
查找順序是首先從application.properties
查找,如果找不到,再查找 application.yml
。
優(yōu)先級(jí):application.properties > application.yml
。
首先,添加依賴。
Maven:
<!-- spring boot config --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
Gradle:
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
配置如下:
erwin.name=馮文議 erwin.age=20 erwin.sex=男 erwin.english-name=Erwin Feng erwin.birthday=1992/02/26 erwin.like=movie,game,music,tea,travel erwin.visitedCities=巴中,揭陽,廣州,從化,成都,三亞,上海,杭州,北京 erwin.moreOther={myWeb:'https://fengwenyi.com',github:'https://github.com/fengwenyi'}
代碼如下:
package com.fengwenyi.spring_boot_config_sample.config; import lombok.Data; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import java.util.*; /** * @author Erwin Feng * @since 2020/8/11 */ @Data @Configuration public class ReadConfigByValue { @Value("${erwin.name}") private String name; @Value("${erwin.age}") private Integer age; @Value("${erwin.sex}") private String sex; @Value("${erwin.english-name}") private String englishName; @Value("${erwin.birthday}") private Date birthday; @Value("${erwin.like}") private List<String> likes; @Value("#{'${erwin.visitedCities}'.split(',')}") private List<String> visitedCities; @Value("#{${erwin.moreOther}}") private Map<String, String> moreOther; }
配置如下(properties格式)
author.name=馮文議 author.age=20 author.sex=男 author.english-name=Erwin Feng author.birthday=1992/02/26 author.like[0]=movie author.like[1]=game author.like[2]=music author.like[3]=tea author.like[4]=travel author.visitedCities=巴中,揭陽,廣州,從化,成都,三亞,上海,杭州,北京 author.moreOther.myWeb=https://fengwenyi.com author.moreOther.github=https://github.com/fengwenyi
配置如下(yaml格式)
author: name: 馮文議-yml age: 20 sex: 男 english-name: Erwin Feng birthday: 1992/02/26 like: - movie - game - music - tea - travel visitedCities: 巴中,揭陽,廣州,從化,成都,三亞,上海,杭州,北京 moreOther: myWeb: https://fengwenyi.com github: https://github.com/fengwenyi
<br />代碼如下:
package com.fengwenyi.spring_boot_config_sample.config; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import java.io.Serializable; import java.util.Date; import java.util.List; import java.util.Map; /** * @author Erwin Feng * @since 2020/8/12 */ @Data @Configuration @ConfigurationProperties(prefix = "author") public class AuthorConfig implements Serializable { private static final long serialVersionUID = 9032405467573421607L; private String name; private Integer age; private String sex; private String englishName; @JsonFormat(pattern = "yyyy/MM/dd") private Date birthday; private List<String> like; private List<String> visitedCities; private Map<String, String> moreOther; }
讀取出來的數(shù)據(jù)展示:
{ "name":"馮文議", "age":20, "englishName":"Erwin Feng", "birthday":"1992/02/26", "likes":[ "movie", "game", "music", "tea", "travel" ], "visitedCities":[ "巴中", "揭陽", "廣州", "從化", "成都", "三亞", "上海", "杭州", "北京" ], "moreOther":{ "myWeb":"https://fengwenyi.com", "github":"https://github.com/fengwenyi" } }
@Autowired private Environment environment;
格式:@Value("${name:defaultValue}")
當(dāng)配置文件找不到這個(gè)配置時(shí),就會(huì)返回默認(rèn)值,如果沒有默認(rèn)值,就會(huì)報(bào)錯(cuò)。
如:@Value("${java.home}")
D:\Java\Java8\jdk1.8.0_251\jre
// 單元測(cè)試-讀取配置文件的值 @Value("${erwin.like}") public void testReadLike(String like, @Value("${erwin.sex}") String sex) { System.out.println("1===>" + like); System.out.println("1===>" + sex); }
參數(shù) like 會(huì)取 @Value("${erwin.like}") 的值 參數(shù) sex 會(huì)取 @Value("${erwin.sex}") 的值 經(jīng)過測(cè)試,多個(gè)方法,執(zhí)行順序是隨機(jī)。 特別注意:這個(gè)只是在啟動(dòng)的時(shí)候執(zhí)行,但是實(shí)際調(diào)用的時(shí)候,還是傳入的值。
方法一:配置文件:
erwin.like=movie,game,music,tea,travel
Java代碼:
@Value("${erwin.like}") private List<String> likes;
方法二:
erwin.visitedCities=巴中,揭陽,廣州,從化,成都,三亞,上海,杭州,北京
Java代碼:
@Value("#{'${erwin.visitedCities}'.split(',')}") private List<String> visitedCities;
配置文件:
erwin.moreOther={myWeb:'https://fengwenyi.com',github:'https://github.com/fengwenyi'}
Java代碼:
@Value("#{${erwin.moreOther}}") private Map<String, String> moreOther;
@Value("#{systemProperties}") private Map<String, String> systemPropertiesMap;
@Component @PropertySource("classpath:values.properties") public class PriorityProvider { private String priority; @Autowired public PriorityProvider(@Value("${priority:normal}") String priority) { this.priority = priority; } // standard getter }
package com.fengwenyi.spring_boot_config_sample.config; import com.fengwenyi.spring_boot_config_sample.support.YamlPropertySourceFactory; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import java.io.Serializable; /** * @author Erwin Feng * @since 2020/8/13 */ @Data @Configuration @ConfigurationProperties(prefix = "db") //@PropertySource({"classpath:config/db.properties"}) @PropertySource(value = {"classpath:config/db.yml"}, factory = YamlPropertySourceFactory.class) public class DBConfig implements Serializable { private static final long serialVersionUID = -6527591545525817929L; /** 服務(wù)器地址 */ private String host; /** 端口 */ private Integer port; /** 數(shù)據(jù)庫名 */ private String dbName; /** 用戶名 */ private String username; /** 密碼 */ private String password; }
配置文件:
db: host: localhost port: 3306 db-name: test username: root password: 123456
說明: 1、@Configuration 表明這是一個(gè)Spring配置,會(huì)注入到Spring容器中。 2、@ConfigurationProperties(prefix = "db") 表示這個(gè)類與配置文件關(guān)聯(lián),其中prefix指明前綴。 3、@PropertySource 這個(gè)指明配置文件的位置,如果沒有這個(gè)配置,則會(huì)從默認(rèn)的配置文件讀取。默認(rèn)的配置文件:application.properties > application.yml。另外,這個(gè)默認(rèn)只支持properties類型的文件,所以,需要配置factory。 4、@PropertySource也可以與@Value結(jié)合使用。
YamlPropertySourceFactory
package com.fengwenyi.spring_boot_config_sample.support; import org.springframework.boot.env.YamlPropertySourceLoader; import org.springframework.core.env.PropertySource; import org.springframework.core.io.support.EncodedResource; import org.springframework.core.io.support.PropertySourceFactory; import java.io.IOException; /** * @author Erwin Feng * @since 2020/8/13 */ public class YamlPropertySourceFactory implements PropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { // 返回 yaml 屬性資源 return new YamlPropertySourceLoader() .load(resource.getResource().getFilename(), resource.getResource()) .get(0); } }
以上是“Spring Boot中如何讀取配置”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。