我有一个项目,其中包含一些主要源代码(读取配置和StartUp-Listener以启动多个服务)和多个子模块。在主项目以及子模块中都有资源文件夹。当前,我必须将application.yml存储在其中一个子模块中。我主要资源中的application.yml被忽略。
项目结构:
-Main
-SubModule1
-Submodule2
-main
-resources
-config
-application.yml_
-Submodule3
-MainSourceCode (including the submodules)
-main
-resources
-config
-application.yml
备注:
整个项目的名称曾经是Submodule2的名称(因此,可能还有一些配置剩余)
如果我将Submodule2中的application.yml_重命名为application.yml,一切正常
那就是我如何读取配置:
@Configuration
@Order(100)
@PropertySources({
@PropertySource(value = "file:../../../../../resources/config/application.yml", ignoreResourceNotFound = true),
@PropertySource("classpath:/config/application.yml")
})
public class AuthorizationControllerConfiguration {
...
我收到输出:
2019-08-28 08:49:58.054 INFO 19812 --- [ main] o.s.c.a.ConfigurationClassParser : Properties location [file:../../../../../resources/config/application.yml] not resolvable: ..\..\..\..\..\resources\config\application.yml (System cannot find file)
2019-08-28 08:49:58.054 WARN 19812 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [de.......AuthorizationControllerConfiguration]; nested exception is java.io.FileNotFoundException: class path resource [config/application.yml] cannot be opened because it does not exist
Config1按预期被忽略,但是Config2是-但是-从SubModule2而不是从主模块读取
因此,基本上我的程序(从IntelliJ btw运行)是从错误的源中选择的。
我必须在哪里查看更改“ classpath”的来源?
最佳答案
不幸的是,@PropertySources
批注不适用于开箱即用的YML文件,请参见此blog
若要解决此问题,您将需要添加一个自定义PropertySourceFactory。
同样,从前面提到的博客文章中:
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
Properties propertiesFromYaml = loadYamlIntoProperties(resource);
String sourceName = name != null ? name : resource.getResource().getFilename();
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
}
private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
try {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
} catch (IllegalStateException e) {
// for ignoreResourceNotFound
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException)
throw (FileNotFoundException) e.getCause();
throw e;
}
}
}
这应该解决该问题。