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");
相关推荐
YsyaaabB5 分钟前
LangChain作业二---多语言翻译Prompt
开发语言·python·langchain
SunnyDays10117 分钟前
如何在 Java 中实现 OFD 与 PDF 格式互转
java·开发语言
keykey6.17 分钟前
用 PyTorch 训练图像分类器:完整实战
开发语言·人工智能·深度学习·机器学习
雪度娃娃18 分钟前
转向现代C++——保证const成员函数的线程安全性
开发语言·c++
原来是猿38 分钟前
深入理解 C++ unordered_map 与 unordered_set
开发语言·c++
满天星830357740 分钟前
【Qt】信号和槽 (一)(概述和基本使用)
开发语言·c++·qt
l1t1 小时前
DeepSeek总结的 waddler,一个 Go 语言编写的从 YAML 文件运行的 ETL 管道
开发语言·golang·etl
小江的记录本1 小时前
【Spring全家桶】Spring Cloud 2023.0.x:微服务核心理论、CAP/BASE定理(附《思维导图》+《面试高频考点清单》)
java·spring boot·后端·spring·spring cloud·微服务·面试
Solis程序员1 小时前
缓存三剑客预防策略
java·spring·缓存