Issue
I need to get absolute path to current active configuration file in Spring boot that don't locate in classpath or resources
It can be located in default place - project folder, subfolder "config", set via spring.config.location and in random place, also in another disk
Something like "E:\projects\configs\myProject\application.yml"
Solution
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 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;
}
Not the best solution I suppose but it works
If you have any idea how to improve it I would be really appreciate it
Answered By - EoinKanro
Answer Checked By - Katrina (JavaFixing Volunteer)