把需要配置的default.ini文件放在项目src下
import java.io.InputStream;
import java.util.Properties;
/**
* 配置信息处理组件-系统静态配置信息处理组件
*/
public class StaticProperties {
//配置信息
private static Properties prop = new Properties();
//锁标记,用于管理调取、清空刷新时的线程同步问题
private static String syncStr = ""+StaticProperties.class;
//初始化
static {
init();
}
/**
* 初始化配置信息
* 默认读取项目源代码路径下/default.ini配置文件
* 如需挂载其他配置文件,需要在此配置文件内,
* 将文件路径编写进Properties.includeFilePath参数,以分号分隔
*/
private static void init(){
synchronized(syncStr){
loadPatch("/default.ini");
String includeFilePath = getProperty("Properties.includeFilePath");
if(includeFilePath!=null){
for(String patch:includeFilePath.split(";")){
loadPatch(patch);
}
}
}
}
/**
* 将给定路径的配置文件信息,加载进配置参数中
* @param patch
*/
private static void loadPatch(String patch){
InputStream is = null;
try {
is = StaticProperties.class.getResourceAsStream(patch);
if(is!=null){
prop.load(is);
}
System.out.println("PropertiesHelper.loadPatch["+patch+"]");
}catch(Exception e){
e.printStackTrace();
}finally{
if(is!=null){
try {
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 按照给定的key获取配置参数
* @param key
* @return
*/
public static String getProperty(String key){
synchronized(syncStr){
return prop.getProperty(key);
}
}
/**
* 获取配置参数
* 备注:获取到的配置参数更改无效
* @return
*/
public static Properties getAllProperty(){
synchronized(syncStr){
return (Properties)prop.clone();
}
}
/**
* 刷新配置参数
* 同步最新配置文件到配置参数中
*/
public static void flush(){
synchronized(syncStr){
prop.clear();
init();
}
}
public static void main(String[] args) {
/*
default.ini 内容为:
Properties.includeFilePath=/app_config/dataSource.ini;/app_config/ip.ini;
ip.ini 内容为:
sendInsBranchID=1000000000
*/
System.out.println(StaticProperties.getProperty("sendInsBranchID"));
//控制台输出结果为1000000000
}
}