1. 饿汉式
public class PropertiesHolderHunger {
private static Properties pros = new Properties();
static {
try {
pros.load(PropertiesHolderHunger.class.getClassLoader().getResourceAsStream(
"config.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static Properties getPros() {
return pros;
}
@Test
public void proTest() throws IOException {
Properties pros = getPros();
String temp = pros.getProperty("LOG_SOURCE_DIR");
System.out.println(temp);
}
}
懒汉式
public class PropertiesHolderLaze {
private static Properties pros = null;
public static Properties getPros() throws IOException {
if (pros==null){
synchronized (PropertiesHolderLaze.class){
if (pros==null){
pros = new Properties();
pros.load(PropertiesHolderLaze.class.getClassLoader().getResourceAsStream(
"config.properties"));
}
}
}
return pros;
}
}
解释
- 获取配置文件的输入流
PropertiesHolderLaze.class.getClassLoader().getResourceAsStream("config.properties")
- synchronized为锁