问题描述
在Spring-boot应用程序中,我只有一个模块,并且能够注入位于src/main/resources
的配置文件,例如“ my.properties”,如下所示:
@Configuration
@PropertySource("/my.properties")
public class MyConf{
}
一切正常,但是后来我创建了子模块,现在我将该配置文件移到了子模块中。 启动主应用程序时,出现以下异常:
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [com.myapp.MainApplication]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/home/jeanvaljean/workspace/mainmodule/secondarymodule/my.properties]
如我所见,我可以通过写来解决问题
@PropertySource("/src/main/resources/my.properties")
这样做,路径是正确的并且可以加载文件。
无论如何,这是一个可怕的解决方案,我很确定有一个更优雅,更灵活的选择。 有什么办法吗?
1楼
Spring对于如何查找资源有几种不同的实现。
通过使用前缀classpath:
您将告诉Spring在所有类路径中搜索资源,而不是在与应用程序捆绑在一起的类中搜索资源。
取决于ApplicationContenxt,Spring将使用不同的默认Resource类。
在您的情况下,Spring似乎正在实例化FileSystemResource
,该文件仅查找具有相对或绝对路径的文件系统上可用的文件(但不在jars中!)。
我的经验法则是,永远不要在同一模块/组件/ jar中添加某些内容,而总是在其前加上classpath:
如果我知道它在不同的模块/组件/ jar中(有些人对此感到恼火:)。
您可以在阅读更多内容。