SpringBoot 如何編寫(xiě)配置文件
我們經(jīng)常在項(xiàng)目開(kāi)放中需要進(jìn)行很多配置, 那么這些配置基本上都是動(dòng)態(tài)的, 如果我直接寫(xiě)在代碼中, 修改起來(lái)很麻煩, 如果該配置在多處進(jìn)行引用啦, 你估計(jì)會(huì)殺了寫(xiě)代碼的人。
那么我們?cè)谑褂肧pringBoot的時(shí)候, 也是需要進(jìn)行配置文件編寫(xiě)的。在spirngBoot里面, 可以有兩種方式聲明配置
1、直接編寫(xiě)配置文件 然后從配置文件里面獲取2、編寫(xiě)配置文件 然后編寫(xiě)bean, 通過(guò)注解注入到bean里面 獲取的時(shí)候從bean里面獲取
配置文件編寫(xiě)可以有多種, 例如我們常見(jiàn)的有: xml、properties、json、yaml.....
我們這里就使用常見(jiàn)的properties文件來(lái)寫(xiě)
編寫(xiě)配置文件,從配置文件里面獲取
創(chuàng)建配置文件
使用配置項(xiàng)
注解說(shuō)明
@PropertySource({'classpath:config/web.properties'}) //指定配置文件@Value('${site.name}') // 獲取配置項(xiàng) value
效果
編寫(xiě)配置文件, 從bean里面獲取
編寫(xiě)bean, WebSetting.java
package com.example.demo.domain;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.PropertySource;import org.springframework.stereotype.Component;@Component@PropertySource(value = 'classpath:config/web.properties', encoding = 'utf-8')@ConfigurationProperties(prefix = 'site') // 這個(gè)可以指定前綴 只要成員屬性能對(duì)上就行 也可以不指定 使用@Value來(lái)獲取public class WebSetting { @Value('${site.name}') private String siteName; @Value('${site.desc}') private String siteDesc; @Value('${site.domain}') private String siteDomain; // 對(duì)上了可以不用@Value private String test; public String getTest() { return test; } public void setTest(String test) { this.test = test; } public String getSiteName() { return siteName; } public void setSiteName(String siteName) { this.siteName = siteName; } public String getSiteDesc() { return siteDesc; } public void setSiteDesc(String siteDesc) { this.siteDesc = siteDesc; } public String getSiteDomain() { return siteDomain; } public void setSiteDomain(String siteDomain) { this.siteDomain = siteDomain; }}
config/web.properties
site.name=憧憬site.domain=aoppp.comsite.desc=這是一個(gè)技術(shù)分享的博客!site.test=test
獲取配置 效果
需要注意點(diǎn)
1、配置文件注入失敗,出現(xiàn)Could not resolve placeholder 解決:根據(jù)springboot啟動(dòng)流程,會(huì)有自動(dòng)掃描包沒(méi)有掃描到相關(guān)注解, 默認(rèn)Spring框架實(shí)現(xiàn)會(huì)從聲明@ComponentScan所在的類(lèi)的package進(jìn)行掃描,來(lái)自動(dòng)注入,因此啟動(dòng)類(lèi)最好放在根路徑下面,或者指定掃描包范圍,spring-boot掃描啟動(dòng)類(lèi)對(duì)應(yīng)的目錄和子目錄
2、注入bean的方式,屬性名稱和配置文件里面的key一一對(duì)應(yīng),就用加@Value 這個(gè)注解,如果不一樣,就要加@value('${XXX}')
以上就是SpringBoot 如何編寫(xiě)配置文件的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot 編寫(xiě)配置文件的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. jsp+servlet實(shí)現(xiàn)猜數(shù)字游戲2. CSS可以做的幾個(gè)令你嘆為觀止的實(shí)例分享3. 讀大數(shù)據(jù)量的XML文件的讀取問(wèn)題4. JSP實(shí)現(xiàn)文件上傳功能5. jsp文件下載功能實(shí)現(xiàn)代碼6. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案7. javascript xml xsl取值及數(shù)據(jù)修改第1/2頁(yè)8. JSP之表單提交get和post的區(qū)別詳解及實(shí)例9. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能10. jsp實(shí)現(xiàn)textarea中的文字保存換行空格存到數(shù)據(jù)庫(kù)的方法
