在Java开发中,可能需要把一些配置参数写入properties配置文件中,在这里介绍一种通过静态内部类单例模式来读取的properties文件的方式。
1.properties文件配置路径
在resources下新建配置文件test.properties,如果对于Java读取指定资源输入流不太了解的话可以先移步至 Java的Class.getClassLoader().getResourceAsStream()与Class.getResourceAsStream()理解。
2.PropertiesUtil工具类
public class PropertiesUtil {
/** 配置文件路径 */
private final static String PROPERTIES_PATH = "test.properties";
private static Properties properties;
private PropertiesUtil() {
readProperties();
}
/* 静态内部类获得外部类实例,在构造方法中读取配置文件 */
private static class PropStaticInner {
private static final PropertiesUtil INSTANCE = new PropertiesUtil();
}
public static PropertiesUtil getInstance() {
return PropStaticInner.INSTANCE;
}
private static void readProperties() {
properties = new Properties();
InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream(PROPERTIES_PATH);
try {
properties.load(in);
} catch (IOException e) {
// 日志和异常处理
} finally {
try {
in.close();
} catch (IOException e) {
// 日志和异常处理
}
}
}
public Properties getProps() {
return properties;
}
}
静态内部类实现单例模式:外部类加载时不会立即加载内部类,就不会去初始化INSTANCE。只有当 getInstance() 方法第一次被调用时,才会加载内部类,从而初始化INSTANCE。
3. 使用方法
Properties props = PropertiesUtil.getInstance().getProps();