Ver Fonte

新增系统环境属性获取工具类

jingyuanchao há 1 ano atrás
pai
commit
f6ccb31ad3

+ 92 - 0
soc-common/soc-common-core/src/main/java/com/xunmei/common/core/utils/PropertiesUtils.java

@@ -0,0 +1,92 @@
+package com.xunmei.common.core.utils;
+
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.context.EnvironmentAware;
+import org.springframework.core.env.Environment;
+import org.springframework.stereotype.Component;
+
+import java.util.MissingResourceException;
+
+
+@Component
+public final class PropertiesUtils implements EnvironmentAware {
+    private static Environment env;
+
+    @Override
+    public void setEnvironment(Environment environment) {
+        PropertiesUtils.env = environment;
+    }
+
+    /**
+     * Get a value based on key , if key does not exist , null is returned
+     *
+     * @param key
+     * @return
+     */
+    public static String getProperty(String key) {
+        try {
+            return env.getProperty(key);
+        } catch (MissingResourceException e) {
+            return null;
+        }
+    }
+
+    /**
+     * Get a value based on key , if key does not exist , null is returned
+     *
+     * @param key
+     * @return
+     */
+    public static String getProperty(String key, String defaultValue) {
+        try {
+            String value = env.getProperty(key);
+            if (StringUtils.isBlank(value)) {
+                return defaultValue;
+            }
+            return value;
+        } catch (MissingResourceException e) {
+            return defaultValue;
+        }
+    }
+
+    /**
+     * 根据key获取值
+     *
+     * @param key
+     * @return
+     */
+    public static int getInt(String key) {
+        return Integer.parseInt(env.getProperty(key));
+    }
+
+    /**
+     * 根据key获取值
+     *
+     * @param key
+     * @param defaultValue
+     * @return
+     */
+    public static int getInt(String key, int defaultValue) {
+        String value = env.getProperty(key);
+        if (StringUtils.isBlank(value)) {
+            return defaultValue;
+        }
+        return Integer.parseInt(value);
+    }
+
+    /**
+     * 根据key获取值
+     *
+     * @param key
+     * @param defaultValue
+     * @return
+     */
+    public static boolean getBoolean(String key, boolean defaultValue) {
+        String value = env.getProperty(key);
+        if (StringUtils.isBlank(value)) {
+            return defaultValue;
+        }
+        return new Boolean(value);
+    }
+
+}