這篇文章主要講解了關(guān)于SpringBoot的外部化配置使用記錄的詳細(xì)解析,內(nèi)容清晰明了,對(duì)此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會(huì)有幫助。
為合山等地區(qū)用戶提供了全套網(wǎng)頁(yè)設(shè)計(jì)制作服務(wù),及合山網(wǎng)站建設(shè)行業(yè)解決方案。主營(yíng)業(yè)務(wù)為做網(wǎng)站、網(wǎng)站建設(shè)、合山網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專(zhuān)業(yè)、用心的態(tài)度為用戶提供真誠(chéng)的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會(huì)得到認(rèn)可,從而選擇與我們長(zhǎng)期合作。這樣,我們也可以走得更遠(yuǎn)!
更新: 工作中突然想起來(lái),關(guān)于Yaml的使用,并不屬于Spring的范疇,是org.yaml.snakeyaml處理的。所以yaml的使用應(yīng)該參考官方,不過(guò)貌似打不開(kāi)。。。
Spring利用snakeyaml將配置解析成PropertySource,然后寫(xiě)入到Environment,就能使用了
記錄下使用SpringBoot配置時(shí)遇到的一些麻煩,雖然這種麻煩是因?yàn)橹R(shí)匱乏導(dǎo)致的。
記錄下避免一段時(shí)間后自己又給忘記了,以防萬(wàn)一。
如果放到博客里能幫助到遇到同樣問(wèn)題的同志,自是極好!
SpringBoot的外部化配置,主要就是指平時(shí)用到的一些配置文件,這些配置由于不是硬編碼,放在了配置文件中,所以相對(duì)來(lái)說(shuō)是一個(gè)外部化的配置Externalized Configuration
SpringBoot官方外部化配置的在線文檔Externalized Configuration
初級(jí)用法#
SpringBoot對(duì)配置提供了極大的便利,僅僅需要編寫(xiě)一個(gè)Yaml文件或者Properties文件,按照其規(guī)定的格式,書(shū)寫(xiě)好我們的配置信息,然后編寫(xiě)一個(gè)相應(yīng)的Java類(lèi),使用注解@ConfigurationProperties和@Configuration配合使用,或者@Configuration和@Value配合使用,即可將配置的值,映射到我們配置類(lèi)或者JavaBean中。
有如下Java配置類(lèi)
@Configuration @ConfigurationProperties(prefix="spring.server") public class AppConfig{ private String name; private String port; public void setName(String name){ this.name = name; } public void setPort(String port){ this.port = port; } }
如下配置文件,
Yaml格式配置文件
# application.yml spring: server: name: spring-app port: 9527
Properties格式配置文件
# application.properties spring.server.name=spring-app spring.server.port=9237
使用@ConfigurationProperties,必須要有Setter方法,綁定時(shí)是通過(guò)Setter方法綁定的
參見(jiàn)
org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor#postProcessBeforeInitialization
,這是一個(gè)BeanPostProcessor
這樣在SpringBoot中,我們就可以將AppConfig這個(gè)Bean注入到別的Bean中使用我們的配置了。
以上這些在開(kāi)發(fā)中基本上也就滿足需要了,大部分我們的配置都很簡(jiǎn)單,通常都是數(shù)值型的和字符串。
但是,凡事不能絕對(duì)。
高級(jí)用法#
以下配置參考這位
Array/List#
假如有如下需求,應(yīng)用僅對(duì)幾個(gè)有限的IP開(kāi)放訪問(wèn),然后我們想把這幾個(gè)獲得許可的IP地址寫(xiě)在配置文件中。
這個(gè)時(shí)候如果配置解析僅僅支持字符串和數(shù)值型的話,就需要我們自己獲取到配置值以后,再去進(jìn)行一些后續(xù)的處理,比如轉(zhuǎn)換成數(shù)組或者列表。
好在,優(yōu)秀的框架,總能滿足大部分的需求,SpringBoot是直接配置直接到數(shù)組或者列表的映射到
使用方式
Java配置類(lèi)#
@Configuration @ConfigurationProperties(prefix="allows") public class AllowedAccessConfig{ private String[] ipList; // 字段類(lèi)型可以是 List<String> public void setPort(String[] port){ this.ipList = ipList; } }
配置文件#
# application.yml allows: ipList: - 192.168.1.1 - 192.168.1.2 - 192.168.1.3 - 192.168.1.4 # or allows: ipList: 192.168.1.1, 192.168.1.2, 192.168.1.3, 192.168.1.4
# application.properties allows.ipList[0]=192.168.1.1 allows.ipList[1]=192.168.1.2 allows.ipList[2]=192.168.1.3 allows.ipList[3]=192.168.1.4 # or allows.ipList= 192.168.1.1, 192.168.1.2, 192.168.1.3, 192.168.1.4
Map#
如果數(shù)組或者列表不滿足需求,需要key-vlaue型的,沒(méi)問(wèn)題,SpringBoot也是支持的。
假設(shè)一個(gè)對(duì)接方不同的業(yè)務(wù),使用了不同的AES密鑰,那么在配置的時(shí)候,就要根據(jù)業(yè)務(wù)類(lèi)型作為key,對(duì)應(yīng)的密鑰作為value。
Java配置類(lèi)#
@Configuration @ConfigurationProperties(prefix="aes.keys") public class AesKeyConfig{ private Map<String,String> keys; public void setKeys(Map<String,String> keys){ this.keys = keys; } }
配置文件#
# application.yml aes: keys: order: 28jsaS2asf2fSA2 pay: @ra@3safdsR5&sDa # or aes: keys[order]: 28jsaS2asf2fSA2 keys[pay]: @ra@3safdsR5&sDa
# application.properties aes.keys.order=28jsaS2asf2fSA2 aes.keys.pay=@ra@3safdsR5&sDa # or aes.keys[order]=28jsaS2asf2fSA2 aes.keys[pay]=@ra@3safdsR5&sDa
Enum#
枚舉?那必須支持
不過(guò)實(shí)際意義不怎么大,如果配置的值要可以轉(zhuǎn)換成枚舉值的話,配置的值必須和枚舉值的name一致,大小寫(xiě)都不能差,因?yàn)镾pringBoot實(shí)現(xiàn)的配置到枚舉的轉(zhuǎn)換,使用的是
/* java.lang.Enum#valueOf */ public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) { // 這里的name就是枚舉值的字符表示,一般都是大寫(xiě)的 T result = enumType.enumConstantDirectory().get(name); if (result != null) return result; if (name == null) throw new NullPointerException("Name is null"); throw new IllegalArgumentException( "No enum constant " + enumType.getCanonicalName() + "." + name); }
關(guān)于這段代碼的理解,可以參考另外一片文章深入理解Java枚舉
如果枚舉還有其他字段的話,就沒(méi)辦法了
JavaBean#
什么? 還是不能滿足?想要直接把配置綁定到一個(gè)JavaBean?
干就完事了!
JavaBean#
@Configuration @ConfigurationProperties(prefix="upload") public class UploadConfig{ private String rootPath; private String fileType; private int fileSize; private boolean rename; // 省略 Setter方法 }
配置文件#
# application.yml upload: root-path: /xx/xx/xx file-type: zip fileSize: 1M rename: false
# application.properties upload.rootPath=/xx/xx/xx upload.fileType=zip upload.fileSize=1M upload.rename=false
以上幾種用法,可以組合使用,非常的靈活
不過(guò)如果是JavaBean的數(shù)組或者List,或者作為Map的value,會(huì)發(fā)現(xiàn)綁定不上去。
原因在于,綁定默認(rèn)是基于Setter方法,進(jìn)行單個(gè)字段的綁定,賦值,而這里要的是一個(gè)JavaBean,需要?jiǎng)?chuàng)建一個(gè)JavaBean對(duì)象,再去做屬性綁定賦值。
如果按照這兩步走,也可以做到成功綁定到一個(gè)作為元素的JavaBean對(duì)象。
只是SpringBoot并沒(méi)有那么做,而是提供了一個(gè)@ConstructorBinding注解,讓我們使用構(gòu)造器綁定數(shù)據(jù)。
復(fù)雜配置#
JavBean#
@Configuration @ConfigurationProperties(prefix="app") public class AppConfig{ private Map<String, DataSourceMetadata> multiDataSourceMap; public void setMultiDataSourceMap(Map<String, DataSourceMetadata> multiDataSourceMap){ this.multiDataSourceMap = multiDataSourceMap; } } public class DataSourceMetadata{ private String url; private String driverClass; private String username; private String passowrd; // 省略Setter和Getter }
配置文件#
app: multiDataSourceMap: ds1: url: jdbc:// driver-class: com.MySQL.cj.Driver username: xxx password: xxx ds2: url: jdbc:// driver-class: com.mysql.cj.Driver username: 12sds password: adfwqw # or app: multiDataSourceMap: ds1: { url: jdbc:// driver-class: com.mysql.cj.Driver username: xxx password: xxx } ds2: { url: jdbc:// driver-class: com.mysql.cj.Driver username: 12sds password: adfwqw }
然后啟動(dòng),走起,立馬會(huì)發(fā)現(xiàn)熟悉又可氣的NPE
原因很簡(jiǎn)單,SpringBoot沒(méi)能從配置文件讀取相應(yīng)的配置數(shù)據(jù)并且實(shí)例化一個(gè)Map,因?yàn)?/p>
它現(xiàn)在面對(duì)的情況比以前復(fù)雜了,現(xiàn)在的JavaBean是一個(gè)Map的value值
解決方法就是使用構(gòu)造器綁定的方式,并且需要在構(gòu)造器使用此注解@ConstructorBinding
public class DataSourceMetadata{ private String url; private String driverClass; private String username; private String passowrd; @ConstructorBinding public DataSourceMetadata(String url, String driverClass, String username, String passowrd){ this.url = url; this.driverClass = driverClass; this.username = username; this.password = password; } // 省略Setter和Getter }
只要這么一搞就正常了,不會(huì)有煩人的NPE
我并不知道是否有別的方式也可以做到,比如繼續(xù)使用Setter方法來(lái)進(jìn)行數(shù)據(jù)綁定
瘦身計(jì)劃#
上面的這些配置,如果都有的話,全部寫(xiě)到application.yml或者application.properties文件中,會(huì)導(dǎo)致配置文件內(nèi)容太多,而且各種配置混合在一起,不便于管理和維護(hù)。
如果需要改動(dòng)某個(gè)配置,就要改動(dòng)整個(gè)文件,存在一定的風(fēng)險(xiǎn)導(dǎo)致其他配置被誤改。
所以應(yīng)該一類(lèi)配置,放到一起去管理。
同樣的,一類(lèi)配置通常對(duì)應(yīng)一個(gè)功能,如果其中一項(xiàng)配置的改動(dòng),那么相應(yīng)的測(cè)試,也能保證同一個(gè)配置文件的修改不會(huì)引發(fā)其他問(wèn)題。
所以有必要將application.yml拆分了。
花了一番力氣,拆分了一個(gè)出來(lái)upload.yml,然后使用如下方式引入配置文件
配置文件默認(rèn)是放在 resources目錄下(maven/gradle),配置文件在編譯打包后,會(huì)位于classes的根目錄下,也就是我們所謂的classpath
@Configuration @PropertySource("classpath:upload.yml") @ConfigurationProperties(prefix="upload") public class UploadConfig{ private String rootPath; private String fileType; private int fileSize; private boolean rename; // 省略 Setter方法 }
問(wèn)題來(lái)了,死活沒(méi)法將數(shù)據(jù)綁定到JavaBean的屬性上。
Debug看源碼,陷進(jìn)去出不來(lái)。試著使用profile來(lái)解決,雖然可以解決,但是畢竟不是同一個(gè)使用場(chǎng)景,并不合適。
最后找人求救,告知@PropertySource不支持yaml文件,僅支持properties,于是試了下,果然是的
SpringBoot版本是2.2.6,有個(gè)群友說(shuō)他1.5的還是支持的,不過(guò)SpringBoot官方明確寫(xiě)到不支持的
2.7.4. YAML Shortcomings#
YAML files cannot be loaded by using the @PropertySource annotation. So, in the case that you need to load values that way, you need to use a properties file.
上面看到,其實(shí)yaml配置更有優(yōu)勢(shì)一些,所以如果想繼續(xù)使用yaml的話,也不是不可以
@PropertySource支持自定義文件格式#
// 這里繼承了DefaultPropertySourceFactory,也可以直接實(shí)現(xiàn)PropertySourceFactory public class YamlPropertySourceFactory extends DefaultPropertySourceFactory { public YamlPropertySourceFactory () { super(); } @Override public PropertySource<?> createPropertySource (String name, EncodedResource resource) throws IOException { // 這個(gè)判斷是有必要的,因?yàn)橹苯邮褂胣ame是null,沒(méi)深究原因 String nameToUse = name != null ? name : resource.getResource().getFilename(); // yml文件,使用YamlPropertiesFactoryBean來(lái)從yaml文件Resource中構(gòu)建一個(gè)Properties對(duì)象 // 然后使用PropertiesPropertySource封裝成PropertySource對(duì)象,就能加入到Environment if (nameToUse.endsWith(".yml")) { YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean(); factoryBean.setResources(resource.getResource()); factoryBean.afterPropertiesSet(); return new PropertiesPropertySource(nameToUse, factoryBean.getObject()); } // 如果不是yml配置文件,使用默認(rèn)實(shí)現(xiàn) return super.createPropertySource(name, resource); } }
使用時(shí),@PropertySource(factory=YamlPropertySourceFactory.class)即可。
使用@Value#
@Value是Spring Framework的注解,不屬于SpringBoot,其典型使用場(chǎng)景就是注入外部化配置屬性,官方文檔@Values介紹
@Value使用Spring內(nèi)建的轉(zhuǎn)化器SimpleTypeConverter,這個(gè)支持Integer,String,和逗號(hào)分割的字符串?dāng)?shù)組。
如果覺(jué)得支持不夠,還是可以自定義轉(zhuǎn)換支持,自定義一個(gè)Converter,然后加入到ConverterService這個(gè)Bean中,因?yàn)楹竺娴腂eanPostProcessor依賴(lài)的就是ConverterService來(lái)處理轉(zhuǎn)換的
所以如果有一些復(fù)雜的配置,最好還是使用SpringBoot的方式。
@Value的優(yōu)勢(shì)在于,它支持SpEL,而且可以使用在任意一個(gè)Bean的方法參數(shù)或者字段上
所以這是兩種不同的使用場(chǎng)景,看情況自己選擇。
不過(guò)總體個(gè)人傾向于前面一種,因?yàn)槿绻谄渌腂ean中直接使用@Value,萬(wàn)一我們要改配置的名字了,結(jié)果因?yàn)槭褂昧薂Value,遍布的到處都是,改起來(lái)很麻煩,所以從管理維護(hù)的角度來(lái)說(shuō),@Value太野了。
順便說(shuō)一下對(duì)@Value的處理位置org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean,當(dāng)然這里也是處理@Inject @Autowired @Resource的地方
后記#
從配置文件到程序中使用到配置的值,一共經(jīng)歷兩大步
如果不滿足properties或者yaml格式的配置,可以自定義PropertySourceLoader,可以參考
org.springframework.boot.env.YamlPropertySourceLoader 和org.springframework.boot.env.PropertiesPropertySourceLoader
補(bǔ)充更新#
在使用@ConfigurationProperties時(shí),可以不用有對(duì)應(yīng)的字段定義,如果需要對(duì)注入的配置值,在Setter方法中轉(zhuǎn)換成其他類(lèi)型時(shí)。
因?yàn)檫@種綁定方式直接通過(guò)Setter方法來(lái)做的(其實(shí)@Value也可以注解在方法上),并不會(huì)檢查是否存在這個(gè)字段的定義。
JavaConfig#
@Configuration @ConfigurationProperties("config") public class Config{ Map<BizType, Metadata> bizMetaMap = new ConcurrentHashMap<>(5); public void setMetadatas(List<Metadata> metas){ for(Metadata meta: metas){ bizMetaMap.put(BizType.forCode(),meta); } } }
yaml配置#
config: metadatas: - name: xxx age: xxx
看完上述內(nèi)容,是不是對(duì)關(guān)于SpringBoot的外部化配置使用記錄的詳細(xì)解析有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
網(wǎng)頁(yè)題目:關(guān)于SpringBoot的外部化配置使用記錄的詳細(xì)解析
轉(zhuǎn)載源于:http://aaarwkj.com/article26/peedcg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供ChatGPT、品牌網(wǎng)站制作、網(wǎng)站策劃、虛擬主機(jī)、網(wǎng)站排名、關(guān)鍵詞優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)