A. spring怎麼載入非classpath路徑下的properties配置文件
java"><beanid="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<propertyname="locations">
<list>
<value>file:D:/workspace/test/conf/jdbc.properties</value>
</list>
</property>
</bean>
B. SpringBoot 如何優雅讀取配置文件10分鍾教你搞定
很多時候我們需要將一些常用的配置信息比如阿里雲 oss 配置、發送簡訊的相關信息配置等等放到配置文件中。
下面我們來看一下 Spring 為我們提供了哪些方式幫助我們從配置文件中讀取這些配置信息。
application.yml 內容如下:
wuhan2020: 2020年初武漢爆發了新型冠狀病毒,疫情嚴重,但是,我相信一切都會過去!武漢加油!中國加油!my-profile:name: Guide哥email: [email protected]:location: 湖北武漢加油中國加油books: -name: 天才基本法description: 二十二歲的林朝夕在父親確診阿爾茨海默病這天,得知自己暗戀多年的校園男神裴之即將出國深造的消息——對方考取的學校,恰是父親當年為她放棄的那所。 -name: 時間的秩序description: 為什麼我們記得過去,而非未來?時間「流逝」意味著什麼?是我們存在於時間之內,還是時間存在於我們之中?卡洛·羅韋利用詩意的文字,邀請我們思考這一亘古難題——時間的本質。 -name: 了不起的我description: 如何養成一個新習慣?如何讓心智變得更成熟?如何擁有高質量的關系? 如何走出人生的艱難時刻?
1.通過 @value 讀取比較簡單的配置信息
使用 @Value("${property}") 讀取比較簡單的配置信息:
@Value("${wuhan2020}")String wuhan2020;
需要注意的是 @value這種方式是不被推薦的,Spring 比較建議的是下面幾種讀取配置信息的方式。
2.通過@ConfigurationProperties讀取並與 bean 綁定
LibraryProperties 類上加了 @Component 註解,我們可以像使用普通 bean 一樣將其注入到類中使用。
importlombok.Getter;importlombok.Setter;importlombok.ToString;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.context.annotation.Configuration;importorg.springframework.stereotype.Component;importjava.util.List;@Component@ConfigurationProperties(prefix ="library")@Setter@Getter@{privateString location;privateList books;@Setter@Getter@ToStringstaticclassBook{ String name; String description; }}
這個時候你就可以像使用普通 bean 一樣,將其注入到類中使用:
packagecn.javaguide.readconfigproperties;importorg.springframework.beans.factory.InitializingBean;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;/** *@authorshuang.kou */@ntsInitializingBean{privatefinalLibraryProperties library;(LibraryProperties library){this.library = library; }publicstaticvoidmain(String[] args){ SpringApplication.run(.class,args); }@(){ System.out.println(library.getLocation()); System.out.println(library.getBooks()); }}
控制台輸出:
湖北武漢加油中國加油[LibraryProperties.Book(name=天才基本法, description........]
3.通過@ConfigurationProperties讀取並校驗
我們先將application.yml修改為如下內容,明顯看出這不是一個正確的 email 格式:
my-profile:name: Guide哥email: koushuangbwcx@
ProfileProperties 類沒有加 @Component 註解。我們在我們要使用ProfileProperties 的地方使用@
EnableConfigurationProperties注冊我們的配置 bean:
importlombok.Getter;importlombok.Setter;importlombok.ToString;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.stereotype.Component;importorg.springframework.validation.annotation.Validated;importjavax.validation.constraints.Email;importjavax.validation.constraints.NotEmpty;/***@authorshuang.kou*/@Getter@Setter@ToString@ConfigurationProperties("my-profile")@{@NotEmptyprivateString name;@Email@NotEmptyprivateString email;//配置文件中沒有讀取到的話就用默認值privateBooleanhandsome =Boolean.TRUE;}
具體使用:
packagecn.javaguide.readconfigproperties;importorg.springframework.beans.factory.InitializingBean;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.boot.context.properties.EnableConfigurationProperties;/** *@authorshuang.kou */@SpringBootApplication@EnableConfigurationProperties(ProfileProperties.class){privatefinalProfileProperties profileProperties;(ProfileProperties profileProperties){this.profileProperties = profileProperties; }publicstaticvoidmain(String[] args){ SpringApplication.run(.class,args); }@(){ System.out.println(profileProperties.toString()); }}
因為我們的郵箱格式不正確,所以程序運行的時候就報錯,根本運行不起來,保證了數據類型的安全性:
Binding to target org.springframework.boot.context.properties.bind.BindException:Failedtobindpropertiesunder'my-profile'to cn.javaguide.readconfigproperties.ProfileProperties failed:Property:my-profile.emailValue:koushuangbwcx@Origin:classpathresource[application.yml]:5:10Reason:mustbeawell-formedemailaddress
我們把郵箱測試改為正確的之後再運行,控制台就能成功列印出讀取到的信息:
ProfileProperties(name=Guide哥, [email protected], handsome=true)
4.@PropertySource讀取指定 properties 文件
importlombok.Getter;importlombok.Setter;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.context.annotation.PropertySource;importorg.springframework.stereotype.Component;@Component@PropertySource("classpath:website.properties")@Getter@SetterclassWebSite{@Value("${url}")privateString url;}
使用:
@Autowiredprivate WebSite webSite;System.out.println(webSite.getUrl());//https://javaguide.cn/
5.題外話:Spring 載入配置文件的優先順序
Spring 讀取配置文件也是有優先順序的,直接上圖:
原文鏈接:https://www.toutiao.com/a6791445278911103500/?log_from=7f5fb8f9b4b47_1640606437752
C. springboot載入自定義properties原理
springboot自定義屬性文件通過value註解引入,和@autowired不同的是,它是由這個來處理,屬性文件的讀取和注入是在BeanDefinition級別,對象實例化之前。
我們建一個簡單的類的梳理一下。
調用堆棧 從refresh開始,主要走了這幾個方法:
invokes
->processConfigBeanDefinitions
ConfigurationClassParser->doProcessConfigurationClass
ConfigurationClassParser->processPropertySource
ConfigurationClassParser->addPropertySource
ConfigurationClassParser主要方法:
doProcessConfigurationClass->processPropertySource->addPropertySource
邏輯主要集中在doProcessConfigurationClass方法
doProcessConfigurationClass負責解析@PropertySource,@Import annotations,@ComponentScan等註解 。
1 調用processPropertySource處理自身的propertySource
2 掃描類上的ComponentScan,對掃出的類繼續調用parse
3 處理@Import annotations等其他標簽
processPropertySource結構很簡單:
1根據註解里的location屬性載入配置文件
2調用addPropertySource處理每個屬性文件
addPropertySource這個類才是真正處理@value屬性:
1把用戶定義的properties文件加到Eniverment中去
2如果有相同name的屬性文件,需要合並
CompositePropertySource 的場景其實是你有兩個不同的文件,但是 @PropertySource中設置同樣的name屬性,這樣CompositePropertySource 會做一個合並,按加入的時間順序取。
增加一個proct2,PropertySource name都設置為myprod
debug到addPropertySource,newSource和existing已經不一樣了。
environment的propertySources里也有兩份文件了。
D. java web啟動時修改並重新載入properties文件
大兄弟,我這兒有一個,你參考一下,但是輸出流問題,沒有得到解決。因為src在項目布置到tomcat上會消失的,所以你看看能不能解決?
E. 在java中如何讀取properties文件
使用java.util.Properties
1、創建一個Properties對象。
2、使用對象的load方法載入你的property文件。
3、使用getProperty方法取值回。
例子:
package com.bill.test;
import java.io.FileInputStream;
import java.util.Properties;
public class Test {
public static void main(String[] args) throws Exception{
答Properties property = new Properties();
property.load(new FileInputStream("你的文件位置"));
String value = property.getProperty("你的屬性的key");
//TODO 使用value...
}
}
F. 如何在Spring容器中載入自定義的配置文件
自定義配置文件
配置文件名為:project.properties,內容如下:
[html] view plain
# 是否開啟邏輯刪除
project_del.filter.on=false
project_domain=
修改Spring配置文件
之前代碼:
[html] view plain
<beanidbeanid="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<propertynamepropertyname="locations">
<list>
<value>classpath:dbinfo.properties</value>
</list>
</property>
</bean>
修改後的配置文件
[html] view plain
<beanidbeanid="propertyConfigurer"
class="com.hisun.core.util.">
<propertynamepropertyname="locations">
<list>
<value>classpath:dbinfo.properties</value>
<value>classpath:project.properties</value>
</list>
</property>
</bean>
加入了classpath:project.properties,其為自定義的配置文件
將PropertyPlaceholderConfigurer類修改為自定義類,
PropertyPlaceholderConfigurer類的具體作用可以查資料這塊兒不做詳細介紹
注意下:這個configurer類獲取的是所有properties的屬性map,如果希望處理某個properties文件,需要在properties中
做一個命名區別,然後在載入的時候,根據key的前綴,進行獲取。
定義類
類的具體內容為下,
[java] view plain
importjava.util.HashMap;
importjava.util.Map;
importjava.util.Properties;
importorg.springframework.beans.BeansException;
importorg.springframework.beans.factory.config.;
importorg.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
publicclass {
privatestatic Map ctxPropertiesMap;
@Override
protectedvoid processProperties( beanFactoryToProcess,
Properties props)throws BeansException {
super.processProperties(beanFactoryToProcess, props);
ctxPropertiesMap =new HashMap();
for(Object key : props.keySet()) {
String keyStr = key.toString();
if(keyStr.startsWith("project_")){
String value = props.getProperty(keyStr);
ctxPropertiesMap.put(keyStr, value);
}
}
}
publicstatic Object getContextProperty(String name) {
returnctxPropertiesMap.get(name);
}
}
定義獲取配置文件中值的類SpringPropertiesUtil
類的具體內容如下:
[java] view plain
importorg.springframework.beans.BeansException;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.ApplicationContextAware;
importorg.springframework.stereotype.Component;
/**
* Spring-PropertiesUtil工具類 -獲取屬性值
*
*/
@Component
publicclass SpringPropertiesUtil {
publicstatic final String KEY = "propertyConfigurer";
privatestatic ApplicationContext applicationContext;
publicvoid setApplicationContext(ApplicationContext applicationContext)
throwsBeansException {
SpringPropertiesUtil.applicationContext = applicationContext;
}
publicstatic ApplicationContext getApplicationContext() {
returnapplicationContext;
}
/**
* 獲取配置文件中的內容
*
* @param keyName
* @return
*/
publicstatic String parseStr(String keyName) {
cp = () applicationContext
.getBean(KEY);
returncp.getContextProperty(keyName).toString();
}
/**
* 獲取配置文件中的內容
*
* @param keyName
* @return
*/
publicstatic int parseInt(String keyName) {
cp = () applicationContext
.getBean(KEY);
returnInteger.parseInt(cp.getContextProperty(keyName).toString());
}
/**
* 獲取配置文件中的內容
*
* @param keyName
* @return
*/
publicstatic double parseDouble(String keyName) {
cp = () applicationContext
.getBean(KEY);
returnDouble.parseDouble(cp.getContextProperty(keyName).toString());
}
}
這樣,在項目當中就能夠方便快速的獲取properties文件中配置的參數
如SpringPropertiesUtil.parseStr(「content」)