java静态类读取配置文件内容

21 篇文章 0 订阅

说明一下,无需导入任何jar包,运用的是jdk自带的ClassLoader加载器,启动加载所有的配置文件内容。

以下是具体的代码:

配置文件:application.properties

server.port=8095
baidu.domain.name=www.baidu.com
test.china=\u4E0D\u9519

PropertyConstants加载配置文件,放入Properties 中
package zjq.utils;

import java.io.IOException;
import java.util.Properties;

public class PropertyConstants {
	private static Properties properties;
	
	private static void setProperty(){
		if (properties==null) {
			properties = new Properties();
			ClassLoader loader = Thread.currentThread().getContextClassLoader();
			try {
				properties.load(loader.getResourceAsStream("application.properties"));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static String getPropertiesKey(String key){
		if (properties==null) {
			setProperty();
		}
		return properties.getProperty(key, "default");
	}
}


配置文件类,无需注解直接调用Constants 

public class Constants {
public static final String SERVER_PORT = PropertyConstants.getPropertiesKey("server.port");
public static final String TEST_CHINA = PropertyConstants.getPropertiesKey("test.china");
}

以上就能实现静态调用配置文件,只需启动加载就行了。


  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值