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");
相关推荐
Javatutouhouduan6 小时前
2026Java面试的正确打开方式!
java·高并发·java面试·java面试题·后端开发·java编程·java八股文
chao1898446 小时前
基于 SPEA2 的多目标优化算法 MATLAB 实现
开发语言·算法·matlab
JAVA面经实录9177 小时前
Java初级最终完整版学习路线图
java·spring·eclipse·maven
赏金术士7 小时前
Kotlin 习题集 · 高级篇
android·开发语言·kotlin
Cat_Rocky8 小时前
k8s-持久化存储,粗浅学习
java·学习·kubernetes
楼兰公子8 小时前
buildroot 在编译rust时裁剪平台类型数量的方法
开发语言·后端·rust
知识领航员8 小时前
蘑兔AI音乐深度实测:功能拆解、实测表现与适用场景
java·c语言·c++·人工智能·python·算法·github
吴声子夜歌8 小时前
Go——并发编程
开发语言·后端·golang
释怀°Believe8 小时前
Spring解析
java·后端·spring
ooseabiscuit8 小时前
Laravel4.x:现代PHP框架的奠基之作
java·开发语言·php