我需要在Spring中获得不位于类路径或资源中的当前活动配置文件的绝对路径
它可以位于默认的place - project文件夹,子文件夹"config",通过spring.config.location设置,也可以位于任意位置,也可以位于另一个磁盘中。
有点像"E:\projects\configs\myProject\application.yml“
发布于 2022-04-07 16:39:50
有一天,我在这里发现了同样的问题,但现在找不到了。
所以我的解决方案,也许有人需要它
@Autowired
private ConfigurableEnvironment env;
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;
}我认为这不是最好的解决方案,但有效。
如果你知道如何改进它,我会非常感激的
发布于 2022-04-07 18:46:03
假设您在application-{env}.yml文件夹中有这些resources配置文件,我们将激活dev配置。
application.yml
application-dev.yml
application-prod.yml
application-test.yml
...有两种方法可以激活dev:
application.yml,spring:
profiles:
active: dev当您想启动应用程序时,
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的绝对路径。
https://stackoverflow.com/questions/71785970
复制相似问题