SpringBoot 如何編寫配置文件
我們經常在項目開放中需要進行很多配置, 那么這些配置基本上都是動態的, 如果我直接寫在代碼中, 修改起來很麻煩, 如果該配置在多處進行引用啦, 你估計會殺了寫代碼的人。
那么我們在使用SpringBoot的時候, 也是需要進行配置文件編寫的。在spirngBoot里面, 可以有兩種方式聲明配置
1、直接編寫配置文件 然后從配置文件里面獲取2、編寫配置文件 然后編寫bean, 通過注解注入到bean里面 獲取的時候從bean里面獲取
配置文件編寫可以有多種, 例如我們常見的有: xml、properties、json、yaml.....
我們這里就使用常見的properties文件來寫
編寫配置文件,從配置文件里面獲取
創建配置文件
使用配置項
注解說明
@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=這是一個技術分享的博客!site.test=test
獲取配置 效果
需要注意點
1、配置文件注入失敗,出現Could not resolve placeholder 解決:根據springboot啟動流程,會有自動掃描包沒有掃描到相關注解, 默認Spring框架實現會從聲明@ComponentScan所在的類的package進行掃描,來自動注入,因此啟動類最好放在根路徑下面,或者指定掃描包范圍,spring-boot掃描啟動類對應的目錄和子目錄
2、注入bean的方式,屬性名稱和配置文件里面的key一一對應,就用加@Value 這個注解,如果不一樣,就要加@value('${XXX}')
以上就是SpringBoot 如何編寫配置文件的詳細內容,更多關于SpringBoot 編寫配置文件的資料請關注好吧啦網其它相關文章!
相關文章:
