通过一个PropertiesUtil类,在tomcat初始化时,对Properties对象props进行初始化(指向对应的配置文件fileName-mmall)
public class PropertiesUtil {
private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
private static Properties props;
//代码块执行顺序:静态 -> 普通 -> 构造
//在tomcat启动时初始化
static {
String fileName = "mmall.properties";
props = new Properties();
try {
props.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName), "UTF-8"));
} catch (IOException e) {
logger.error("配置文件读取异常", e);
}
}
public static String getProperty(String key){
String value = props.getProperty(key.trim());
if(StringUtils.isBlank(value)){
return null;
}
return value.trim();
}
public static String getProperty(String key,String defaultValue){
String value = props.getProperty(key.trim());
if(StringUtils.isBlank(value)){
value = defaultValue;
}
return value.trim();
}
}
读取value时,就通过props.getProperty(String key)返回的value来返回(除此之外可以再进行额外的操作-比如去空或判空)
fileName-mmall.properties配置文件:
使用: