本篇內(nèi)容主要講解“Springboot怎么指定獲取配置properties文件的值”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“Springboot怎么指定獲取配置properties文件的值”吧!
創(chuàng)新互聯(lián)為企業(yè)級客戶提高一站式互聯(lián)網(wǎng)+設(shè)計服務(wù),主要包括成都做網(wǎng)站、成都網(wǎng)站制作、成都外貿(mào)網(wǎng)站建設(shè)、重慶APP軟件開發(fā)、小程序開發(fā)、宣傳片制作、LOGO設(shè)計等,幫助客戶快速提升營銷能力和企業(yè)形象,創(chuàng)新互聯(lián)各部門都有經(jīng)驗豐富的經(jīng)驗,可以確保每一個作品的質(zhì)量和創(chuàng)作周期,同時每年都有很多新員工加入,為我們帶來大量新的創(chuàng)意。

test.number=123456789
這里我們采取最直接的方式(也可以通過注解獲取),特意準(zhǔn)備了個工具類 PropertiesUtil.java :
package com.test.webflux.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
/**
* 配置文件讀取
*
* @Author: JCccc
* @Des: ElegantDay
*/
public class PropertiesUtil {
private static Logger log = LoggerFactory.getLogger(PropertiesUtil.class);
private static Properties props;
//項目根目錄文件夾內(nèi)讀取
// static {
// if (props == null) {
// props = new Properties();
// try {
// props.load(new FileInputStream("/testDemo/config/test_config.properties"));
// } catch (IOException e) {
// log.error("配置文件讀取異常", e);
// }
// }
// }
//resource文件夾內(nèi)讀取
static {
String fileName = "test_config.properties";
props = new Properties();
try {
props.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName), "UTF-8"));
} catch (IOException e) {
log.error("配置文件讀取異常", e);
}
}
/**
* 根據(jù)配置文件中的key獲取value
* @param key
* @return
*/
public static String getProperty(String key) {
String value = props.getProperty(key.trim());
if (StringUtils.isEmpty(value)) {
return null;
}
return value.trim();
}
/**
* 根據(jù)配置文件中的key獲取value (當(dāng)獲取不到值賦予默認(rèn)值)
* @param key
* @param defaultValue
* @return
*/
public static String getProperty(String key, String defaultValue) {
String value = props.getProperty(key.trim());
if (StringUtils.isEmpty(value)) {
value = defaultValue;
}
return value.trim();
}
public static void main(String[] args) {
System.out.println("配置文件中有key&value:"+PropertiesUtil.getProperty("test.number"));
System.out.println("配置文件無有key&value,賦予默認(rèn)值"+PropertiesUtil.getProperty("test.numberNone","默認(rèn)值 JCccc"));
}
}
到此,相信大家對“Springboot怎么指定獲取配置properties文件的值”有了更深的了解,不妨來實際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
當(dāng)前標(biāo)題:Springboot怎么指定獲取配置properties文件的值
轉(zhuǎn)載注明:http://www.chinadenli.net/article12/gghhgc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供商城網(wǎng)站、外貿(mào)建站、面包屑導(dǎo)航、電子商務(wù)、企業(yè)網(wǎng)站制作、微信公眾號
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)