【问题标题】:Spring Boot - get current configuration file path in runtimeSpring Boot - 在运行时获取当前配置文件路径
【发布时间】:2022-07-22 01:51:28
【问题描述】:

我需要获取 Spring boot 中当前活动配置文件的绝对路径,这些文件不在类路径或资源中

它可以位于默认位置 - 项目文件夹,子文件夹“config”,通过 spring.config.location 设置和随机位置,也可以在另一个磁盘中

类似“E:\projects\configs\myProject\application.yml”的东西

【问题讨论】:

    标签: spring-boot configuration-files


    【解决方案1】:

    假设您在resources 文件夹中有这些application-{env}.yml 配置配置文件,我们将激活dev 配置。

    application.yml
    application-dev.yml
    application-prod.yml
    application-test.yml 
    ...
    

    您可以通过两种方式激活dev:

    1. 修改你的application.yml,
    spring:
      profiles:
        active: dev
    
    1. 或在您想要启动应用程序时通过命令行:
    java -jar -Dspring.profiles.active=dev application.jar
    

    然后,在您的程序中尝试以下代码:

        // get the active config dynamically
        @Value("${spring.profiles.active}")
        private String activeProfile;
    
        public String readActiveProfilePath() {
            try {
                URL res = getClass().getClassLoader().getResource(String.format("application-%s.yml", activeProfile));
                if (res == null) {
                    res = getClass().getClassLoader().getResource("application.yml");
                }
                File file = Paths.get(res.toURI()).toFile();
                return file.getAbsolutePath();
            } catch (Exception e) {
                // log the error.
                return "";
            }
        }
    

    输出将是application-dev.yml的绝对路径

    【讨论】:

    • 我想过。我们可以尝试使用“*.yml”在项目文件夹中递归查找文件。但是谁说配置是活动的?...我的第一个解决方案是硬编码 - jar 文件附近的配置文件。但我找到了动态的方式
    • 我已经改进了我的答案。希望对你有帮助
    【解决方案2】:

    有一天我在这里发现了同样的问题,但现在找不到了

    所以这是我的解决方案,也许有人需要它

        @Autowired
        private ConfigurableEnvironment env;
        private static final String YAML_NAME = "application.yml";
    
        private String getYamlPath() throws UnsupportedEncodingException {
            String projectPath = System.getProperty("user.dir");
            String decodedPath = URLDecoder.decode(projectPath, "UTF-8");
    
            //Get all properies
            MutablePropertySources propertySources = env.getPropertySources();
    
            String result = null;
            for (PropertySource<?> source : propertySources) {
                String sourceName = source.getName();
                
                //If configuration loaded we can find properties in environment with name like
                //"Config resource '...[absolute or relative path]' via ... 'path'"
                //If path not in classpath -> take path in brackets [] and build absolute path
    
                if (sourceName.contains("Config resource 'file") && !sourceName.contains("classpath")) {
                    String filePath = sourceName.substring(sourceName.indexOf("[") + 1, sourceName.indexOf("]"));
                    if (Paths.get(filePath).isAbsolute()) {
                        result = filePath;
                    } else {
                        result = decodedPath + File.separator + filePath;
                    }
                    break;
                }
            }
    
            //If configuration not loaded - return default path
            return result == null ? decodedPath + File.separator + YAML_NAME : result;
        }
    
    

    我认为这不是最好的解决方案,但它确实有效

    如果您知道如何改进它,我将不胜感激

    【讨论】:

      猜你喜欢
      • 2011-02-26
      • 1970-01-01
      • 2019-11-14
      • 2019-01-25
      • 1970-01-01
      • 2019-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多