PropertiesUtils工具类
用于获取.properties或者.yml文件的值
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* @Classname PropertiesUtils
* @Description TODO
* @date 2020/11/20 10:52
* @author by 廖青
*/
public class PropertiesUtils {
private static Logger logger = LoggerFactory.getLogger(PropertiesUtils.class);
private static Map<String,Properties> propertiesMap = new HashMap<String,Properties>();
/**
* 默认yml后缀文件名称
*/
private final static String DEFAULT_YML_NAME = "application.yml";
/**
* 默认properties后缀文件名称
*/
private final static String DEFAULT_PROPERTIES_NAME = "application.properties";
/**
* Yaml 文件转换
* @param yamlFileName
*/
private static void setYamlPropertiesToMap(String yamlFileName){
if (StringUtils.isBlank(yamlFileName)) {
throw new RuntimeException(yamlFileName + "不能为空");
}
try {
YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
yamlFactory.setResources(new ClassPathResource(yamlFileName));
propertiesMap.put(yamlFileName,yamlFactory.getObject());
} catch (Exception e) {
logger.error("转换异常:",e);
}
}
/**
* Properties 文件转换
* @param propertiesFileName
*/
private static void setPropertiesToMap(String propertiesFileName){
if (StringUtils.isBlank(propertiesFileName)) {
throw new RuntimeException(propertiesFileName + "不能为空");
}
try {
propertiesMap.put(propertiesFileName, PropertiesLoaderUtils.loadAllProperties(propertiesFileName)); ;
} catch (IOException e) {
logger.error("IO异常:",e);
}
}
/**
* 获取yml配置文件中的值
*
* @param key 需要获取的键名
* @return 对应的值
*/
public static String getConfigByYml(String key) {
return getConfigByYml(key,DEFAULT_YML_NAME);
}
/**
* 获取yml配置文件中的值
*
* @param key 需要获取的键名
* @param configName 自定义配置文件yml后缀的名称
* @return 对应的值
*/
public static String getConfigByYml(String key, String configName) {
if(!propertiesMap.containsKey(configName)){
setYamlPropertiesToMap(configName);
}
return propertiesMap.get(configName).getProperty(key);
}
/**
* 获取properties配置文件中的值
*
* @param key 需要获取的键
* @return 对应的值
*/
public static String getConfigByProperties(String key) {
return getConfigByProperties(key,DEFAULT_PROPERTIES_NAME);
}
/**
* 获取properties配置文件中的值
*
* @param key 需要获取的键
* @param configName properties配置文件的名称
* @return 对应的值
*/
public static String getConfigByProperties(String key, String configName) {
if(!propertiesMap.containsKey(configName)){
setPropertiesToMap(configName);
}
return propertiesMap.get(configName).getProperty(key);
}
}