Spring詳解四種加載配置項的方法
本文默認(rèn) spring 版本是 spring5
1 spring 加載 yml 文件
2 spring 加載 properties 文件
3 spring 加載 系統(tǒng)磁盤 文件
4 spring 加載 xml 文件
5 Java 基于 InputStream 讀取 properties 配置文件
spring框架默認(rèn)加載配置:
resources 下的文件名稱為application
的 application.yml 以及 application.properties, 默認(rèn)會被spring加載到容器 Container
中,如果他們有重復(fù)的配置項,會被默認(rèn)合并,并且 application.properties優(yōu)先級更高. 下面的 LoadYmlTest.java
有詳細(xì)解釋
示例:
# application.yml
user:
userName: ifredom_name
age: 30 # 定義了屬性 age
# application.properties
# 也定義了屬性 age
user.age=99
user.sex=2
package com.example.commonmybatisplus.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; /** * 配置類 * spring默認(rèn)規(guī)則:自動將 resources 下名稱為 application 的 yml 和 properties 文件加載為bean * 注意: 一定要有 get 和 set 方法,此處通過 @Data 注解注入 */ @Data @Configuration @ConfigurationProperties(prefix = "user") public class LoadPropertySourceYmlConfig { private String userName; private int sex; private int age; }
package com.example.commonmybatisplus.PropertySourceTest; import com.example.commonmybatisplus.config.LoadPropertySourceYmlConfig; import com.example.commonmybatisplus.entity.UserEntity; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.env.Environment; /** * 測試 * 從結(jié)果可知: age的值為99,證明了 properties的優(yōu)先級高于yml * 事實上,spring最早支持 properties 類型文件,后來才支持的yml,所以為了兼容 * 一定是 properties > yml 優(yōu)先級。 * 即便將來又出現(xiàn)了 XXX.abc 文件 * 那么為了兼容,永遠(yuǎn)時最早支持的優(yōu)先級更高,也就是 properties > yml >abc */ @SpringBootTest public class LoadYmlTest { @Autowired private LoadPropertySourceYmlConfig ymlConfig; @Test public void testYml() { String name = ymlConfig.getUserName(); int sex = ymlConfig.getSex(); int age = ymlConfig.getAge(); System.out.println(name); // ifredom System.out.println(sex); // 2 System.out.println(age); // 99 } }
1.spring加載yml文件
上面已經(jīng)通過默認(rèn)的方式演示了如何加載默認(rèn)的application.yml,但是更好的寫法是,將我們自定義的配置獨立為一個單獨的文件。
比如我們開發(fā)微信公眾號,小程序開發(fā)時,就需要用到配置,此時的配置就應(yīng)該獨立為一個額外的文件。(此處將演示加載為 List)
一共有3步:
- 創(chuàng)建配置文件
wechat-config.yml
- 定義配置類
LoadPropertySourceYmlConfig
,用來加載yml中的數(shù)據(jù) (指定配置類的加載器) (因為 spring 配置類的默認(rèn)加載器是 PropertiesLoader加載器,所以我們需要自定義 yml加載器??梢宰孕胁榭醋⒔?@PropertySource 源碼) - 自定義配置類加載器
YamlSourceFactory
,繼承Spring提供的默認(rèn)配置類構(gòu)造器DefaultPropertySourceFactory
- 測試
示例:
# main/resources/chat-config.yml
#微信小程序的appid
appid: app-xxx
#微信小程序的Secret
secret: secretxxx
#微信小程序消息服務(wù)器配置的token
token: token-xxx
#微信小程序消息服務(wù)器配置的EncodingAESKey
aesKey: aesKey-xxxwx:
configs:
#微信小程序的appid
- appid: app1
#微信小程序的Secret
secret: secret1
#微信小程序消息服務(wù)器配置的token
token: token1
#微信小程序消息服務(wù)器配置的EncodingAESKey
aesKey: aesKey1#微信小程序的appid
- appid: appid2
#微信小程序的Secret
secret: secret2
#微信小程序消息服務(wù)器配置的token
token: token2
#微信小程序消息服務(wù)器配置的EncodingAESKey
aesKey: aesKey2def-my-var1: 定義配置屬性var1
def-my-var2: 定義配置屬性var2
這里需要注意,在上面的配置文件中是 wx.configs, 因此在配置類中,也必須用同名的 configs 來接收
package com.example.commonmybatisplus.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.io.support.PropertySourceFactory; import org.springframework.stereotype.Component; import java.util.List; /** * 注意:factory的值,為接下來自定義的加載器 */ @Data @Configuration @PropertySource(value = "classpath:wechat-config.yml", factory = YamlSourceFactory.class) @ConfigurationProperties(prefix = "wx") public class LoadPropertySourceYmlConfig { private List<Config> configs; @Data public static class Config { private String appid; private String secret; private String token; private String aesKey; } private String appid; private String secret; private String token; private String aesKey; }
// 自定義記載器 package com.example.commonmybatisplus.config; import org.springframework.boot.env.YamlPropertySourceLoader; import org.springframework.core.env.PropertySource; import org.springframework.core.io.support.DefaultPropertySourceFactory; import org.springframework.core.io.support.EncodedResource; import java.io.IOException; import java.util.List; public class YamlSourceFactory extends DefaultPropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { // 這里使用Yaml配置加載類來讀取yml文件信息 List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource()); return sources.get(0); } }
測試結(jié)果
package com.example.commonmybatisplus.PropertySourceTest; import com.example.commonmybatisplus.config.LoadPropertySourceYmlConfig; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; /** * @Author ifredomvip@gmail.com * @Date 2022/6/15 10:40 * @Version 1.0.0 * @Description **/ @SpringBootTest public class LoadYmlTest { @Autowired private LoadPropertySourceYmlConfig ymlConfig; @Test public void testYml() { String appidXXX = ymlConfig.getAppid(); String secretXXX = ymlConfig.getSecret(); System.out.println("單獨的屬性配置---appidXXX: " + appidXXX); System.out.println("單獨的屬性配置---secretXXX: " + secretXXX); // 以下演示 配置項作為 List List<LoadPropertySourceYmlConfig.Config> configs = ymlConfig.getConfigs(); // 迭代 List 每一項 for (LoadPropertySourceYmlConfig.Config config : configs) { System.out.println("屬性作為List: " + config); } // 獲取List種的某一項 LoadPropertySourceYmlConfig.Config configFirst = configs.get(0); String appidFirst = configFirst.getAppid(); System.out.println("List的第一項: " + configFirst); System.out.println("List的第一項的其中一個屬性: " + appidFirst); LoadPropertySourceYmlConfig.Config configSecond = configs.get(1); String secretSecond = configSecond.getSecret(); System.out.println("List的第二項: " + configSecond); System.out.println("List的第二項的其中一個屬性: " + secretSecond); } }
2.spring 加載 properties 文件
從上一步我們已經(jīng)知道了, spring 默認(rèn)使用 properties 文件的加載器。因此,我們可以少一步構(gòu)造加載器
- 創(chuàng)建配置文件
alibaba-config.properties
- 定義配置類
LoadPropertySourceConfig
,用來加載yml中的數(shù)據(jù) - 測試
# main/resources/alibaba-config.properties
ali-yun.username="ifredom"
ali-yun.password="123456"
ali-yun.blog="http://www.ifredom.com"
package com.example.commonmybatisplus.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Data @Configuration @PropertySource("classpath:alibaba-config.properties") @ConfigurationProperties(prefix = "aliyun") public class LoadPropertySourceConfig { private String username; private String password; private String blog; }
測試:
package com.example.commonmybatisplus.PropertySourceTest; import com.example.commonmybatisplus.config.LoadPropertySourceConfig; import com.example.commonmybatisplus.config.LoadPropertySourceYmlConfig; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; /** * @Author ifredomvip@gmail.com * @Date 2022/6/15 10:40 * @Version 1.0.0 * @Description **/ @SpringBootTest public class LoadYmlTest { @Autowired private LoadPropertySourceYmlConfig ymlConfig; @Autowired private LoadPropertySourceConfig propertyConfig; @Test public void testProperty() { String username = propertyConfig.getUsername(); String password = propertyConfig.getPassword(); String blog = propertyConfig.getBlog(); System.out.println("單獨的屬性配置---username: " + username); System.out.println("單獨的屬性配置---password: " + password); System.out.println("單獨的屬性配置---blog: " + blog); } @Test public void testYml() { } }
細(xì)心的同學(xué)應(yīng)該發(fā)現(xiàn)了,在配置文件中定義的是ali-yun
中間明明有一個短橫線,讀取屬性的時候怎么沒了?
這是因為 Spring 配置加載器類對諸如 空格,下劃線,短橫線,大小寫都做了替空處理,也就是:配置文件是不分大小寫的; 并且 下劃線,短橫線也會忽略: user_name -> username, pass-word -> password
.因此取名你可以很隨意
3.spring加載系統(tǒng)磁盤(properties)文件
有時候我們會需要加載其他項目下的數(shù)據(jù)庫,而配置文件并不在當(dāng)前項目路勁下,因此需要指定文件路徑。
- 磁盤路徑可以是相對路徑,絕對路徑,也可以通過系統(tǒng)屬性值指定變量
- 相對路徑,文件在應(yīng)用根目錄下:
@PropertySource(value = {"file:project1.properties"})
- 相對路徑,文件在應(yīng)用根目錄下:
@PropertySource(value = {"file:./project1.properties"})
- 絕對路徑,在指定的路徑下:
@PropertySource(value = {"file:D:\\project\\project1.properties"})
- 通過系統(tǒng)屬性值指定變量:
@PropertySource(value = {"file:${user.dir}/project1.properties"})
由于加載xml文件還需要對xml文件進行解析,此處不做講解。僅僅使用 properties 文件做例子。 示例:
# 位于D盤下的配置文件 D:\project1.properties
driverClassName=com.mysql.cj.jdbc.Driver
url="https://www.ifredom.com"
username="ifredom"
password="123456"
由于配置文件沒有前綴,因此 配置類 必須使用@Value()
進行映射
package com.example.commonmybatisplus.config; import lombok.Data; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Data @Configuration @PropertySource(value = {"file:D:\\project1.properties"}) public class LoadDiskConfig { @Value("driverClassName") private String driverClassName; @Value("url") private String url; @Value("username") private String username; @Value("password") private String password; }
/** * 測試 */ @SpringBootTest public class LoadYmlTest { @Autowired private LoadDiskConfig diskConfig; @Test public void testDisk() { String username = diskConfig.getUsername(); String url = diskConfig.getUrl(); System.out.println(username); System.out.println(url); } }
4.spring加載xml文件
- 創(chuàng)建一個xml文件:
applicationContext.xml
,并在其中定義一個bean - 通過
ApplicationContext
來加載讀取xml文件
不再推介使用 xml 來讀取文件了,過于復(fù)雜
示例:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "> <bean id="blog" name="author" class="com.example.commonmybatisplus.entity.UserEntity"> <property name="id" value="1"/> <property name="name" value="ifredom"/> <property name="age" value="30"/> </bean> </beans>
@Data public class UserEntity { private Long id; private String name; private int sex; private int age; }
@SpringBootTest public class LoadYmlTest { @Test public void testXml() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserEntity author = context.getBean("author", UserEntity.class); System.out.println(author.getName()); } }
5.Java基于InputStream讀取properties配置文件
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.List; import java.util.Properties; @SpringBootTest public class LoadYmlTest { @Test public void testInputStream() throws IOException { Properties properties = new Properties(); // 使用InPutStream流讀取properties文件 BufferedReader bufferedReader = new BufferedReader(new FileReader("D:/project1.properties")); properties.load(bufferedReader); // 獲取key對應(yīng)的value值 String driverClassName = properties.getProperty("driverClassName"); String username = properties.getProperty("username"); System.out.println(driverClassName); System.out.println(username); } }
到此這篇關(guān)于Spring詳解四種加載配置項的方法的文章就介紹到這了,更多相關(guān)Spring加載配置項內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
ElasticSearch創(chuàng)建后索引修改數(shù)據(jù)類型方法步驟
Elasticsearch存儲數(shù)據(jù)之前需要先創(chuàng)建索引,類似于結(jié)構(gòu)型數(shù)據(jù)庫建庫建表,創(chuàng)建索引時定義了每個字段的索引方式和數(shù)據(jù)類型,這篇文章主要給大家介紹了關(guān)于ElasticSearch創(chuàng)建后索引修改數(shù)據(jù)類型的方法步驟,需要的朋友可以參考下2023-09-09java中利用List的subList方法實現(xiàn)對List分頁(簡單易學(xué))
本篇文章主要介紹了java中l(wèi)ist數(shù)據(jù)拆分為sublist實現(xiàn)頁面分頁的簡單代碼,具有一定的參考價值,有需要的可以了解一下。2016-11-11Springboot導(dǎo)入本地jar后 打包依賴無法加入的解決方案
這篇文章主要介紹了Springboot導(dǎo)入本地jar后 打包依賴無法加入的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11Spring Boot 定義系統(tǒng)啟動任務(wù)的多種方式
這篇文章主要介紹了Spring Boot 定義系統(tǒng)啟動任務(wù)的多種方式,看看你都會哪幾種 ,感興趣的朋友跟隨小編一起看看吧2019-04-04IDEA 中創(chuàng)建SpringBoot 父子模塊的實現(xiàn)
這篇文章主要介紹了IDEA 中創(chuàng)建SpringBoot 父子模塊的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04如何解決UnsupportedOperationException異常問題
這篇文章主要介紹了如何解決UnsupportedOperationException異常問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05java實現(xiàn)一次性壓縮多個文件到zip中的方法示例
這篇文章主要介紹了java實現(xiàn)一次性壓縮多個文件到zip中的方法,涉及java針對文件批量壓縮相關(guān)的文件判斷、遍歷、壓縮等操作技巧,需要的朋友可以參考下2019-09-09