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");
相关推荐
FQNmxDG4S4 小时前
Java多线程编程:Thread与Runnable的并发控制
java·开发语言
前端老石人5 小时前
HTML 字符引用完全指南
开发语言·前端·html
matlab_xiaowang5 小时前
Redux 入门:JavaScript 可预测状态管理库
开发语言·javascript·其他·ecmascript
虹科网络安全5 小时前
艾体宝干货|数据复制详解:类型、原理与适用场景
java·开发语言·数据库
axng pmje5 小时前
Java语法进阶
java·开发语言·jvm
rKWP8gKv76 小时前
Java微服务性能监控:Prometheus与Grafana集成方案
java·微服务·prometheus
老前端的功夫6 小时前
【Java从入门到入土】28:Stream API:告别for循环的新时代
java·开发语言·python
qq_435287926 小时前
第9章 夸父逐日与后羿射日:死循环与进程终止?十个太阳同时值班的并行冲突
java·开发语言·git·死循环·进程终止·并行冲突·夸父逐日
小江的记录本6 小时前
【Kafka核心】架构模型:Producer、Broker、Consumer、Consumer Group、Topic、Partition、Replica
java·数据库·分布式·后端·搜索引擎·架构·kafka
止语Lab6 小时前
从手动到框架:Go DI 演进的三个拐点
开发语言·后端·golang