项目中经常遇到配置基础信息放到配置文件中(如图项目配置文件中的配置路径)
// 项目中获取文件路径实例
String path = Global.getConfig(VIDEO_DATA_LOCATION);
/** * Global配置类 */ public class Global { /** * 当前对象实例 */ private static Global global = new Global(); /** * 保存全局属性值 */ private static Map<String, String> map = Maps.newHashMap(); /** * 属性文件加载对象 */ private static PropertiesLoader loader = new PropertiesLoader("jeesite.properties");
/** * 获取配置 */ public static String getConfig(String key) { String value = map.get(key); if (value == null){ value = loader.getProperty(key); map.put(key, value != null ? value : StringUtils.EMPTY); } return value; }
}
/** * Properties文件载入工具类. 可载入多个properties文件 */ public class PropertiesLoader { private static Logger logger = LoggerFactory.getLogger(PropertiesLoader.class); private static ResourceLoader resourceLoader = new DefaultResourceLoader(); private final Properties properties; public PropertiesLoader(String... resourcesPaths) { properties = loadProperties(resourcesPaths); } public Properties getProperties() { return properties; } /** * 取出Property,但以System的Property优先,取不到返回空字符串. */ private String getValue(String key) { String systemProperty = System.getProperty(key); if (systemProperty != null) { return systemProperty; } if (properties.containsKey(key)) { return properties.getProperty(key); } return ""; } /** * 取出String类型的Property,但以System的Property优先,如果都为Null则抛出异常. */ public String getProperty(String key) { String value = getValue(key); if (value == null) { throw new NoSuchElementException(); } return value; }}