Home > Net >  Spring Boot - get current configuration file path in runtime
Spring Boot - get current configuration file path in runtime

Time:04-08

I need to get absolute path to current active configuration file in Spring boot that don't locate in classpath or resources

Also need to get file if it set through spring.config.location and locate in another disk

Something like "E:\projects\myProject\application.yml"

CodePudding user response:

Assume that you have these application-{env}.yml profiles in resources folder

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

try this

    @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 "";
        }
    }

CodePudding user response:

Someday I found same question here, but cant find it now

So here my solution, maybe someone needs it

    @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 it in environment properties 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;
    }

Not the best solution I suppose but it works

If you have any idea how to improve it I would be really appreciate it

  • Related