properties控制参数,properties中为第一层控制,再设计一个类默认的参数类,使在properties不设置目标值时读取该配置类的值.
1.建立一个properties文件:PropConstantsBas.properties,
2.我们设计一个类,由此类读取properties中的参数,当properties中没有设置或设置为空时,我们在在此类中给予默认值
package com.fanl.sys.Core.bas.config.properties;
import com.fanl.sys.Util.config.properties.PropertiesConfigContants;
/**
* @Description :公用基类参数
* @Author fanl
* @Date 2018/4/24
* @Detail Description :
*/
public class PropConstantsBas extends PropertiesConfigContants {
static {
init("properties/core/bas/PropConstantsBas.properties");
}
/**
* 平台中文名
*/
public final static String FPro_Bas_Pro_Name =
setProperty("fpro.bas.pro.name", "项目名称");
/**
* 租户代码
*/
public final static String FPro_Bas_Tenant_Code =
setProperty("fpro.bas.tenant.code", "PiLi");
/**
* 企业集团代码
*/
public final static String FPro_Bas_Tenant_Group_Code =
setProperty("fpro.bas.tenant.group.code", "PiLi");
/**
* 企业集团名称
*/
public final static String FPro_Bas_Tenant_Group_Name =
setProperty("fpro.bas.tenant.group.name", "霹雳");
}
3.设计一个公共类,在初始加载时便读取配置文件了的值
package com.fanl.sys.Util.config.properties;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* @Description :参数变量基类
* @Author fanl
* @Date 2018/4/24
* @Detail Description :对参数变量类初始化
*/
public class PropertiesConfigContants {
protected static Properties p = new Properties();
protected static void init(String propertyFileName) {
InputStream in = null;
try {
in = PropertiesConfigContants.class.getClassLoader().getResourceAsStream(propertyFileName);
if (in != null){
p.load(in);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 设置配置文件值
* @param key properties文件配置字段名
* @param defaultValue 默认值
* @return
*/
protected static String setProperty(String key, String defaultValue) {
return p.getProperty(key, defaultValue);
}
/**
* 根据key值得到配置文件的值
* @param key properties文件配置字段名
* @return
*/
protected static String getProperty(String key) {
return p.getProperty(key);
}
}
4.然后直接获取配置的值
System.out.println(PropConstantsBas.FPro_Bas_Pro_Name);
System.out.println(PropConstantsBas.FPro_Bas_Tenant_Group_Name);