【问题标题】:Using Spring @PropertySource in a Maven submodule在 Maven 子模块中使用 Spring @PropertySource
【发布时间】:2015-07-26 19:25:25
【问题描述】:

在 Spring-boot 应用程序中,我只有一个模块,并且能够注入配置文件,例如“my.properties”,位于src/main/resources,如下:

@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")

这样做,路径正确,可以加载文件了。

无论如何,这是一个糟糕的解决方案,我很确定还有一个更优雅、更灵活的替代方案。有什么解决办法吗?

【问题讨论】:

  • 您可以尝试将代码更改为@PropertySource("classpath:/my.properties") 吗?从命令行或内部和 IDE 运行 maven 时是否出现此错误?
  • 嘿,这解决了问题。您能在答案中解释原因吗?

标签: java spring maven resources pom.xml


【解决方案1】:

Spring 对如何查找资源有几种不同的实现。通过使用前缀 classpath:,您告诉 Spring 在所有类路径中搜索资源,而不是在与您的应用程序捆绑的类中。

根据 ApplicationContext,Spring 将使用不同的默认资源类。在您的情况下,Spring 正在实例化一个FileSystemResource,它只在文件系统上找到具有相对或绝对路径的可用文件(但不在 jar 中!)。我的经验法则是,如果它位于同一个模块/组件/jar 中,则永远不要为其添加前缀,并且如果我知道它位于不同的模块/组件/jar 中,则始终以 classpath: 为前缀(有些人对此很生气:)。

您可以在Spring Documentation - Resources阅读更多内容

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-10
    • 2019-10-07
    • 2014-02-11
    • 1970-01-01
    • 2015-01-26
    • 2016-08-05
    • 2019-04-15
    • 1970-01-01
    相关资源
    最近更新 更多