解决spring boot读取自定义配置文件的办法

注解的办法虽然够用,但是对于老项目移植时兼容不是很好,所以可以写一个简单粗暴的类解决。
首先,在工具类中创建一个读取配置文件的工具类SystemConfigReader

public class SystemConfigReader {
	private static Properties prop = null;


	public static void init() {
		try {
			ClassPathResource classPathResource = new ClassPathResource("conf.properties");
			prop = new Properties();	
				InputStream is = classPathResource.getInputStream();
				prop.load(is);
				is.close();			
		} catch (Exception e) {
			System.out
					.println("Can't read file stream, file name is conf.properties");
			e.printStackTrace();
		}
	}

	public static Properties getProp() {
		if (null == prop)
			init();
		return prop;
	}

	/**
	 * 
	 * @param key
	 * @return string value of the key
	 */

	/**
	 * get value by key
	 * 
	 * @param key
	 * @return
	 */
	public static String getValueByKey(String key) {
		getProp();
		String s = prop.getProperty(key);

		if (null != s) {
			return s.trim();
		} else {
			System.out.println(" mino key value not founded , the key is :"
					+ key);
			return "";
		}
	}
}

读取的时候只需调用SystemConfigReader.getValueByKey(“key”)方法,也可以改造把方法抽象出来,做一个读取任意配置文件的工具类,都很简单,时间有限,我就不详细叙述了,第一次写博客,希望大家能用得到。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值