擷取yml的可以參考這篇:
Springboot 指定擷取出 yml檔案裡面的配置值
直接進入正題,
先建立一個 配置檔案test_config.properties:
test.number=123456789
接下來擷取test.number對應的值,
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;
//項目根目錄檔案夾内讀取
// static {
// if (props == null) {
// props = new Properties();
// try {
// props.load(new FileInputStream("/testDemo/config/test_config.properties"));
// } catch (IOException e) {
// log.error("配置檔案讀取異常", e);
// }
// }
// }
//resource檔案夾内讀取
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);
}
}
/**
* 根據配置檔案中的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();
}
/**
* 根據配置檔案中的key擷取value (當擷取不到值賦予預設值)
* @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,賦予預設值"+PropertiesUtil.getProperty("test.numberNone","預設值 JCccc"));
}
}