本篇内容主要讲解“Springboot怎么指定获取配置properties文件的值”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Springboot怎么指定获取配置properties文件的值”吧!
test.number=123456789
这里我们采取最直接的方式(也可以通过注解获取),特意准备了个工具类 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;
//项目根目录文件夹内读取
// 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"));
}
}
到此,相信大家对“Springboot怎么指定获取配置properties文件的值”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4579283/blog/4351024