Explorar el Código

properties 加载方式优化

xuxueli hace 8 años
padre
commit
09908bbe92

+ 11 - 30
xxl-job-admin/src/main/java/com/xxl/job/admin/core/util/PropertiesUtil.java Ver fichero

2
 
2
 
3
 import org.slf4j.Logger;
3
 import org.slf4j.Logger;
4
 import org.slf4j.LoggerFactory;
4
 import org.slf4j.LoggerFactory;
5
+import org.springframework.core.io.ClassPathResource;
6
+import org.springframework.core.io.Resource;
7
+import org.springframework.core.io.support.EncodedResource;
8
+import org.springframework.core.io.support.PropertiesLoaderUtils;
5
 
9
 
6
-import java.io.FileInputStream;
7
 import java.io.IOException;
10
 import java.io.IOException;
8
-import java.io.InputStreamReader;
9
-import java.net.URL;
10
 import java.util.Properties;
11
 import java.util.Properties;
11
 
12
 
12
 /**
13
 /**
16
 public class PropertiesUtil {
17
 public class PropertiesUtil {
17
 	private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
18
 	private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
18
 	private static final String file_name = "xxl-job-admin.properties";
19
 	private static final String file_name = "xxl-job-admin.properties";
19
-	
20
-	/**
21
-	 * load properties
22
-	 * @param propertyFileName
23
-	 * @return
24
-	 */
25
-	public static Properties loadProperties(String propertyFileName) {
26
-		Properties prop = new Properties();
27
-		InputStreamReader  in = null;
20
+
21
+
22
+	public static String getString(String key) {
23
+		Properties prop = null;
28
 		try {
24
 		try {
29
-			URL url = null;
30
-			ClassLoader loder = Thread.currentThread().getContextClassLoader();
31
-			url = loder.getResource(propertyFileName); 
32
-			in = new InputStreamReader(new FileInputStream(url.getPath()), "UTF-8");
33
-			prop.load(in);
25
+			Resource resource = new ClassPathResource(file_name);
26
+			EncodedResource encodedResource = new EncodedResource(resource,"UTF-8");
27
+			prop = PropertiesLoaderUtils.loadProperties(encodedResource);
34
 		} catch (IOException e) {
28
 		} catch (IOException e) {
35
 			logger.error(e.getMessage(), e);
29
 			logger.error(e.getMessage(), e);
36
-		} finally {
37
-			if (in != null) {
38
-				try {
39
-					in.close();
40
-				} catch (IOException e) {
41
-					logger.error(e.getMessage(), e);
42
-				}
43
-			}
44
 		}
30
 		}
45
-		return prop;
46
-	}
47
-
48
-	public static String getString(String key) {
49
-		Properties prop = loadProperties(file_name);
50
 		if (prop!=null) {
31
 		if (prop!=null) {
51
 			return prop.getProperty(key);
32
 			return prop.getProperty(key);
52
 		}
33
 		}