获取yml的可以参考这篇:
Springboot 指定获取出 yml文件里面的配置值
www.tuohang.net/article/198309.html
直接进入正题:
先创建一个 配置文件test_config.properties:
1 |
test.number= 123456789 |
接下来获取test.number对应的值
这里我们采取最直接的方式(也可以通过注解获取),特意准备了个工具类 PropertiesUtil.java :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
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" )); } } |
OK,测试下工具类的main方法:
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
原文链接:https://blog.csdn.net/qq_35387940/article/details/90714123
查看更多关于Springboot 如何指定获取自己写的配置properties文件的值的详细内容...