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");
相关推荐
码农颜14 分钟前
5.4.1 锁分类
java·数据库·mysql
牛艺翔1 小时前
C++基础
开发语言·c++
键盘会跳舞1 小时前
C++ :容器适配器stack源码级拆解
开发语言·c++··stack·先进后出
linux-hzh1 小时前
百日算法修炼 · Day 03
java·算法
美味蛋炒饭.2 小时前
Git 版本控制(下)
开发语言·git·学习·总结·后端开发
我星期八休息2 小时前
网络编程—网络层
开发语言·前端·网络·人工智能·智能路由器
不负岁月无痕2 小时前
简单理解操作系统结构
java·linux·c语言·开发语言·c++·面试
mister_guo2 小时前
Java线程池参数应该如何设置(ThreadPoolExecutor)
java
余额瞒着我当琳2 小时前
C++模板初阶与STL初探
android·java·c++
SomeB1oody2 小时前
【RustyML入门】2.9. MeanShift
开发语言·后端·机器学习·rust·教程