您的位置:首页 > 编程语言 > Java开发

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

2016-12-15 16:55 483 查看
说明一下,无需导入任何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");
}


以上就能实现静态调用配置文件,只需启动加载就行了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: