SpringBoot 根据不同环境切换不同文件路径

最简单的办法就是使用多个 application.yml 配置文件 。一个叫 application-test.yml 测试用;另一个是正式使用的 application-prod.yml 。win环境下大部分是开发测试时候使用的,服务正式上线需要部署在Linux服务器上又换成了Linux。但开发初期或者项目不是很正式,也可以不这样写,就单独写一个application.yml 里面写好两个路径,再写一个文件配置类,在这里面写好方法就行。

application.yml

XML 复制代码
file:
  path:
    windows: D:\qr_code_duct\qr_code_back\ddinguia\server\files\
    linux: /app/files/

文件配置类 FileProperties

java 复制代码
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "file")
public class FileProperties {

    private PathConfig path;

    public PathConfig getPath() {
        return path;}

    public void setPath(PathConfig path) {
        this.path = path;}

    public static class PathConfig {
        private String windows;
        private String linux;

        public String getWindows() {
            return windows;}

        public void setWindows(String windows) {
            this.windows = windows;}

        public String getLinux() {
            return linux;}

        public void setLinux(String linux) {
            this.linux = linux;}
    }

    public String getSavePath() {
        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains("win")) {
            return path.getWindows();
        } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
            return path.getLinux();
        } else {
            throw new IllegalStateException("Unsupported operating system: " + os);
        }
    }
}

具体在代码中使用,就像正常调用参数一样就行,比如先在Service层里面引入

java 复制代码
    @Resource
    private FileProperties fileProperties;

然后直接使用即可:

java 复制代码
File directory = new File(fileProperties.getSavePath() + File.separator + fileType + "s");
相关推荐
不可求~5 分钟前
多模型路由怎么落地:把任务分流写进项目的最小实现
java·前端·数据库
mldong1 小时前
用 DDD 设计工作流引擎:聚合根与充血模型
java·架构
mqiqe2 小时前
AgentScope Java Harness:4. 双层记忆系统 让 Agent 拥有真正的“长期大脑“
java·开发语言
伍一512 小时前
03-文件管理模块-一个看似简单的模块藏着多少细节
java·ruoyi·若依
gugucoding2 小时前
46. 【Java】JUC并发工具:让并发更简单
java·开发语言
Nebula_g3 小时前
JavaSE基础语法:面向对象高级(代码中的成分)
java·开发语言·编程·javase·技术栈·高级语法
for_ever_love__3 小时前
python基础语法学习: 异常的传递性
开发语言·python·学习
AC赳赳老秦3 小时前
公开图片 OCR 数据提取:OpenClaw 合规采集公开信息图,识别文字与表格并转化为结构化数据
java·大数据·前端·数据库·python·php·openclaw
依然鸣3 小时前
PTA团体程序设计天梯赛L1真题讲解L1-077-080
开发语言·c++·算法·深度优先·pat考试·图论
byxdaz4 小时前
QT中服务使用
开发语言·qt