SpringBoot 如何編寫配置文件
我們經(jīng)常在項目開放中需要進(jìn)行很多配置, 那么這些配置基本上都是動態(tài)的, 如果我直接寫在代碼中, 修改起來很麻煩, 如果該配置在多處進(jìn)行引用啦, 你估計會殺了寫代碼的人。
那么我們在使用SpringBoot的時候, 也是需要進(jìn)行配置文件編寫的。在spirngBoot里面, 可以有兩種方式聲明配置
1、直接編寫配置文件 然后從配置文件里面獲取2、編寫配置文件 然后編寫bean, 通過注解注入到bean里面 獲取的時候從bean里面獲取
配置文件編寫可以有多種, 例如我們常見的有: xml、properties、json、yaml.....
我們這里就使用常見的properties文件來寫
編寫配置文件,從配置文件里面獲取
創(chuàng)建配置文件
使用配置項
注解說明
@PropertySource({'classpath:config/web.properties'}) //指定配置文件@Value('${site.name}') // 獲取配置項 value
效果
編寫配置文件, 從bean里面獲取
編寫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') // 這個可以指定前綴 只要成員屬性能對上就行 也可以不指定 使用@Value來獲取public class WebSetting { @Value('${site.name}') private String siteName; @Value('${site.desc}') private String siteDesc; @Value('${site.domain}') private String siteDomain; // 對上了可以不用@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=這是一個技術(shù)分享的博客!site.test=test
獲取配置 效果
需要注意點
1、配置文件注入失敗,出現(xiàn)Could not resolve placeholder 解決:根據(jù)springboot啟動流程,會有自動掃描包沒有掃描到相關(guān)注解, 默認(rèn)Spring框架實現(xiàn)會從聲明@ComponentScan所在的類的package進(jìn)行掃描,來自動注入,因此啟動類最好放在根路徑下面,或者指定掃描包范圍,spring-boot掃描啟動類對應(yīng)的目錄和子目錄
2、注入bean的方式,屬性名稱和配置文件里面的key一一對應(yīng),就用加@Value 這個注解,如果不一樣,就要加@value('${XXX}')
以上就是SpringBoot 如何編寫配置文件的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot 編寫配置文件的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. React+umi+typeScript創(chuàng)建項目的過程2. .Net core 的熱插拔機(jī)制的深入探索及卸載問題求救指南3. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp4. SharePoint Server 2019新特性介紹5. 三個不常見的 HTML5 實用新特性簡介6. 解決ASP中http狀態(tài)跳轉(zhuǎn)返回錯誤頁的問題7. ASP中常用的22個FSO文件操作函數(shù)整理8. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁9. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過程解析10. ASP編碼必備的8條原則
