-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPropertyUtil.java
More file actions
63 lines (55 loc) · 1.93 KB
/
PropertyUtil.java
File metadata and controls
63 lines (55 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.util;
import lombok.extern.slf4j.Slf4j;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 读取项目内指定的properties文件
*/
@Slf4j
public class PropertyUtil {
private static final String PROPERTIES_FILE_NAME ="jdbc.properties";
private static Properties props= new Properties();
static{
log.info("执行静态代码块loadProps(),保存在jvm中,避免多次执行。");
loadProps();
}
synchronized static private void loadProps(){
log.info("开始加载properties文件内容.......");
// props = new Properties();
InputStream in = null;
try {
// <!--第一种,通过类加载器进行获取properties文件流,路径为相对路径-->
in = PropertyUtil.class.getClassLoader().getResourceAsStream(PROPERTIES_FILE_NAME);
// <!--第二种,通过类进行获取properties文件流-->
//in = PropertyUtil.class.getResourceAsStream("propertiesFileName");
props.load(in);
} catch (FileNotFoundException e) {
log.error("properties文件未找到");
} catch (IOException e) {
log.error("出现IOException");
} finally {
try {
if(null != in) {
in.close();
}
} catch (IOException e) {
log.error("properties文件流关闭出现异常");
}
}
log.info("加载properties文件内容完成...........");
}
public static String getProperty(String key){
if(null == props) {
loadProps();
}
return props.getProperty(key);
}
public static String getProperty(String key, String defaultValue) {
if(null == props) {
loadProps();
}
return props.getProperty(key, defaultValue);
}
}