소스 검색

PropertiesUtils

wangyunpeng 3 주 전
부모
커밋
4b8c8c92dc

+ 12 - 12
core/src/main/java/com/tzld/supply/util/AliOssFileTool.java

@@ -1157,7 +1157,7 @@ public class AliOssFileTool extends AliOssConfig {
 //		Date expiration = new Date(new Date().getTime() +( 60) * 1000);
         // 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
 
-        URL url = getOssReadOnlyClient().generatePresignedUrl(BasePropertiesUtils.getVideoBucket(),
+        URL url = getOssReadOnlyClient().generatePresignedUrl(PropertiesUtils.getVideoBucket(),
                 filePath, expiration, HttpMethod.GET);
         String path = url.getFile();
         if (StringUtils.startsWith(path, "/")) {
@@ -1169,7 +1169,7 @@ public class AliOssFileTool extends AliOssConfig {
 
     public static String saveObjectFromInternal(InputStream inputStream, String fullKey)
             throws OSSException, ClientException, IOException {
-        String bucketName = BasePropertiesUtils.getVideoBucket();
+        String bucketName = PropertiesUtils.getVideoBucket();
         getInternalOssClient().putObject(bucketName, fullKey, inputStream);
         return fullKey;
     }
@@ -1278,7 +1278,7 @@ public class AliOssFileTool extends AliOssConfig {
             return -1;
         }
         String realPath = path.replace(PropertiesUtils.getDownloadDomain(), "");
-        String bucketName = BasePropertiesUtils.getVideoBucket();
+        String bucketName = PropertiesUtils.getVideoBucket();
         ObjectMetadata objectMetadata = null;
         try {
             objectMetadata = getInternalOssClient().getObjectMetadata(bucketName, realPath);
@@ -1312,7 +1312,7 @@ public class AliOssFileTool extends AliOssConfig {
 
 
     public static Map<String, Object> getMediaAllInfo(String inPath) {
-        return getMediaAllInfo(inPath, BasePropertiesUtils.getVideoBucket());
+        return getMediaAllInfo(inPath, PropertiesUtils.getVideoBucket());
     }
 
     public static Map<String, Object> getMediaAllInfo(String inPath, String bucketName) {
@@ -1414,11 +1414,11 @@ public class AliOssFileTool extends AliOssConfig {
 
     public static StsTokenVO getStsToken(String fileName, Long durationSeconds) {
 
-        String endpoint = BasePropertiesUtils.getLongvideoStsEndpoint();
-        String accessKeyId = BasePropertiesUtils.getLongvideoStsAccessKeyId();
-        String accessKeySecret = BasePropertiesUtils.getLongvideoStsAccessKeySecret();
-        String roleArn = BasePropertiesUtils.getLongvideoStsRoleArn();
-        String roleSessionName = BasePropertiesUtils.getLongvideoStsSessionName();
+        String endpoint = PropertiesUtils.getLongvideoStsEndpoint();
+        String accessKeyId = PropertiesUtils.getLongvideoStsAccessKeyId();
+        String accessKeySecret = PropertiesUtils.getLongvideoStsAccessKeySecret();
+        String roleArn = PropertiesUtils.getLongvideoStsRoleArn();
+        String roleSessionName = PropertiesUtils.getLongvideoStsSessionName();
         StsTokenVO result = new StsTokenVO();
         try {
             String region = "cn-hangzhou";
@@ -1433,7 +1433,7 @@ public class AliOssFileTool extends AliOssConfig {
             if (Objects.nonNull(durationSeconds)) {
                 request.setDurationSeconds(durationSeconds);
             }
-            JSONObject policy = getUploadFileStsPolicy(BasePropertiesUtils.getVideoBucket(), fileName);
+            JSONObject policy = getUploadFileStsPolicy(PropertiesUtils.getVideoBucket(), fileName);
             request.setPolicy(policy.toJSONString());
 
             final AssumeRoleResponse response = client.getAcsResponse(request);
@@ -1445,11 +1445,11 @@ public class AliOssFileTool extends AliOssConfig {
             result.setFileName(fileName);
             result.setHost(AliOssConfig.getUploadDomain());
 
-            String host0 = BasePropertiesUtils.getOssaccelerateUploadDomain();
+            String host0 = PropertiesUtils.getOssaccelerateUploadDomain();
             String host1 = "https://" + AliOssConfig.getBucket(EnumPublicBuckets.PUBBUCKET.getBucketName()) + "." + AliOssConfig.getOssEndPoint() + "/";
             result.setHosts(new String[]{host0, host1});
 
-            result.setBucket(BasePropertiesUtils.getVideoBucket());
+            result.setBucket(PropertiesUtils.getVideoBucket());
             result.setRegion(region);
             result.setCname(true);
 

+ 0 - 72
core/src/main/java/com/tzld/supply/util/BasePropertiesUtils.java

@@ -1,72 +0,0 @@
-package com.tzld.supply.util;
-
-import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.lang3.StringUtils;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Properties;
-
-@Slf4j
-public class BasePropertiesUtils {
-
-    public static Properties properties;
-
-    static {
-        Properties mainProperties = new Properties();
-        properties = new Properties();
-        try {
-            InputStream mainStream = BasePropertiesUtils.class.getClassLoader().getResourceAsStream("application.properties");
-            mainProperties.load(mainStream);
-            // 先通过虚拟机参数 -Denv=value去取配置文件的值
-            // 如果没有设置-Denv的虚拟机参数则说明是本地开发环境,则读取application.properties文件中spring.profiles.active的值
-            String env = System.getProperty("env");
-            if (StringUtils.isEmpty(env)) {
-                env = mainProperties.getProperty("spring.profiles.active");
-            }
-            if (StringUtils.isEmpty(env)) {
-                log.error("设置spring.profiles.active or 设置虚拟机启动参数 -Denv错误!!!");
-                System.exit(1);
-            }
-            InputStream activeStream = BasePropertiesUtils.class.getClassLoader().getResourceAsStream("application.properties");
-            properties.load(activeStream);
-            log.info("开发环境为: " + env);
-        } catch (IOException e) {
-            log.error(e.getMessage());
-            System.exit(1);
-        }
-    }
-
-    public static Properties getProperties() {
-        return properties;
-    }
-
-    public static String getVideoBucket() {
-        return getProperties().getProperty("oss.video.bucket");
-    }
-
-    public static String getLongvideoStsEndpoint() {
-        return getProperties().getProperty("oss.longvideo.video.sts.endpoint");
-    }
-
-    public static String getLongvideoStsAccessKeyId() {
-        return getProperties().getProperty("oss.longvideo.video.sts.accessKeyId");
-    }
-
-    public static String getLongvideoStsAccessKeySecret() {
-        return getProperties().getProperty("oss.longvideo.video.sts.accessKeySecret");
-    }
-
-    public static String getLongvideoStsRoleArn() {
-        return getProperties().getProperty("oss.longvideo.video.sts.roleArn");
-    }
-
-    public static String getLongvideoStsSessionName() {
-        return getProperties().getProperty("oss.longvideo.video.sts.roleSessionName");
-    }
-
-    public static String getOssaccelerateUploadDomain() {
-        return getProperties().getProperty("oss.accelerate.upload.domain");
-    }
-
-}

+ 101 - 18
core/src/main/java/com/tzld/supply/util/PropertiesUtils.java

@@ -2,42 +2,97 @@ package com.tzld.supply.util;
 
 import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang3.StringUtils;
+import org.yaml.snakeyaml.Yaml;
 
 import java.io.IOException;
 import java.io.InputStream;
+import java.util.Map;
 import java.util.Properties;
 
 @Slf4j
 public class PropertiesUtils {
-
     public static Properties properties;
+    public static Properties mainProperties;
 
     static {
-        Properties mainProperties = new Properties();
+        mainProperties = new Properties();
         properties = new Properties();
         try {
-            InputStream mainStream = PropertiesUtils.class.getClassLoader().getResourceAsStream("application.properties");
-            mainProperties.load(mainStream);
-            // 先通过虚拟机参数 -Denv=value去取配置文件的值
-            // 如果没有设置-Denv的虚拟机参数则说明是本地开发环境,则读取application.properties文件中spring.profiles.active的值
+            // 加载主配置文件 application.yml
+            InputStream mainStream = PropertiesUtils.class.getClassLoader().getResourceAsStream("application.yml");
+            if (mainStream == null) {
+                throw new IOException("application.yml 配置文件不存在");
+            }
+            // 解析 YAML 并转换为 Properties 格式(扁平 key-value)
+            Map<String, Object> mainYamlMap = new Yaml().load(mainStream);
+            mainProperties = convertYamlToProperties(mainYamlMap);
+
+            // 获取环境变量(优先取 -Denv,其次取 application.yml 中的 spring.profiles.active)
             String env = System.getProperty("env");
             if (StringUtils.isEmpty(env)) {
                 env = mainProperties.getProperty("spring.profiles.active");
             }
             if (StringUtils.isEmpty(env)) {
-                log.error("设置spring.profiles.active or 设置虚拟机启动参数 -Denv错误!!!");
+                log.error("请设置 spring.profiles.active 或启动参数 -Denv");
                 System.exit(1);
             }
-            InputStream activeStream = PropertiesUtils.class.getClassLoader().getResourceAsStream("application-" + env + ".properties");
-            properties.load(activeStream);
-            properties.put("spring.profiles.active", env);
+
+            // 加载环境配置文件 application-{env}.yml
+            InputStream activeStream = PropertiesUtils.class.getClassLoader().getResourceAsStream("application-" + env + ".yml");
+            if (activeStream == null) {
+                throw new IOException("application-" + env + ".yml 配置文件不存在");
+            }
+            Map<String, Object> activeYamlMap = new Yaml().load(activeStream);
+            Properties activeProperties = convertYamlToProperties(activeYamlMap);
+
+            // 合并配置(环境配置覆盖主配置)
+            properties.putAll(mainProperties);
+            properties.putAll(activeProperties);
+            properties.setProperty("spring.profiles.active", env); // 确保环境变量生效
             log.info("开发环境为: " + env);
+
         } catch (IOException e) {
-            log.error(e.getMessage());
+            log.error("配置文件加载失败: " + e.getMessage(), e);
             System.exit(1);
         }
     }
 
+    /**
+     * 将 YAML 解析后的嵌套 Map 转换为扁平的 Properties(键名用点分隔层级)
+     * 例如: {oss: {supply: {accessKey: "xxx"}}} → "oss.supply.accessKey" = "xxx"
+     */
+    private static Properties convertYamlToProperties(Map<String, Object> yamlMap) {
+        Properties properties = new Properties();
+        flattenYamlMap(yamlMap, "", properties);
+        return properties;
+    }
+
+    /**
+     * 递归展平 YAML Map
+     */
+    private static void flattenYamlMap(Map<String, Object> yamlMap, String parentKey, Properties properties) {
+        for (Map.Entry<String, Object> entry : yamlMap.entrySet()) {
+            String key = parentKey.isEmpty() ? entry.getKey() : parentKey + "." + entry.getKey();
+            Object value = entry.getValue();
+
+            if (value instanceof Map<?, ?>) {
+                // 递归处理嵌套 Map
+                flattenYamlMap((Map<String, Object>) value, key, properties);
+            } else if (value instanceof Iterable<?>) {
+                // 处理列表(转换为逗号分隔的字符串)
+                StringBuilder sb = new StringBuilder();
+                for (Object item : (Iterable<?>) value) {
+                    if (sb.length() > 0) sb.append(",");
+                    sb.append(item);
+                }
+                properties.setProperty(key, sb.toString());
+            } else {
+                // 基本类型直接设置
+                properties.setProperty(key, value != null ? value.toString() : "");
+            }
+        }
+    }
+
     public static Properties getProperties() {
         return properties;
     }
@@ -50,7 +105,6 @@ public class PropertiesUtils {
         return PropertiesUtils.getProperties().getProperty(key);
     }
 
-
     public static boolean getSwaggerEnabled() {
         return Boolean.parseBoolean(getProperties().getProperty("swagger.enabled"));
     }
@@ -59,16 +113,10 @@ public class PropertiesUtils {
         return getProperties().getProperty("swagger.basePath");
     }
 
-
     public static String getSwaggerProtocols() {
         return getProperties().getProperty("swagger.protocols");
     }
 
-
-    public static String getVideoBucket() {
-        return getProperties().getProperty("oss.longvideo.bucket");
-    }
-
     public static String getDownloadDomain() {
         return getProperties().getProperty("oss.longvideo.cdnDomain");
     }
@@ -89,4 +137,39 @@ public class PropertiesUtils {
         return getProperties().getProperty("oss.video.readonly.secretKey");
     }
 
+    public static Properties getMainProperties() {
+        return mainProperties;
+    }
+
+    public static String getMainPropertiesValue(String key) {
+        return getMainProperties().getProperty(key);
+    }
+
+    public static String getVideoBucket() {
+        return getMainProperties().getProperty("oss.video.bucket");
+    }
+
+    public static String getLongvideoStsEndpoint() {
+        return getMainProperties().getProperty("oss.longvideo.video.sts.endpoint");
+    }
+
+    public static String getLongvideoStsAccessKeyId() {
+        return getMainProperties().getProperty("oss.longvideo.video.sts.accessKeyId");
+    }
+
+    public static String getLongvideoStsAccessKeySecret() {
+        return getMainProperties().getProperty("oss.longvideo.video.sts.accessKeySecret");
+    }
+
+    public static String getLongvideoStsRoleArn() {
+        return getMainProperties().getProperty("oss.longvideo.video.sts.roleArn");
+    }
+
+    public static String getLongvideoStsSessionName() {
+        return getMainProperties().getProperty("oss.longvideo.video.sts.roleSessionName");
+    }
+
+    public static String getOssaccelerateUploadDomain() {
+        return getMainProperties().getProperty("oss.accelerate.upload.domain");
+    }
 }