gpt4 book ai didi

java - 为什么Spring的PropertySource会抛出FileNotFoundException?

转载 作者:行者123 更新时间:2023-11-30 02:44:43 26 4
gpt4 key购买 nike

我正在尝试使用 Spring 加载属性文件,该文件位于我的 WEB-INF 文件夹中。

我收到以下错误:

org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [com.elastictest.config.ProdConfig]; nested exception is java.io.FileNotFoundException: \WEB-INF\config\prod.properties (The system cannot find the path specified)

这是我的生产配置文件:

@Configuration
@Profile("prod")
@PropertySource("file:${prodPropertiesFile}")
public class ProdConfig {

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}

}

这是我的 web.xml 声明:

<context-param>
<param-name>prodPropertiesFile</param-name>
<param-value>/WEB-INF/config/prod.properties</param-value>
</context-param>

我已经打开了 war 并验证了属性文件位于 WEB-INF/config 文件夹下。有什么想法吗?

最佳答案

locations您在 @PropertySource 中指定注释由 ResourceLoader 处理。在这种情况下,这将是您的 AnnotationConfigWebApplicationContext ,因为这是一个 Web 应用程序,并且您想要使用注释配置。

作为 ResourceLoader 实现,AnnotationConfigWebApplicationContext 知道如何解析位置值以查找和初始化 Resource对象。它使用这些来创建 ResourcePropertySource用于属性解析的对象。

位置值解析遵循以下几个步骤:

  • 如果它以 / 开头,它会被解释为 servlet 上下文资源,Spring 会尝试通过 ServletContext#getResourceAsStream 检索它。 .

  • 如果它以 classpath: 开头,它会被解释为类路径资源,Spring 会尝试通过 ClassLoader#getResourceAsStream 检索它。 ,给定适当的ClassLoader

  • 否则,它会将分辨率推迟到 UrlResource它使用 URL 来定位资源。它的 javadoc 指出

    Supports resolution as a URL and also as a File in case of the "file:" protocol.

在您的情况下,您在位置前添加了 file: 前缀,因此 Spring 尝试使用 UrlResource。您的路径有一个前导 /,文件系统会将其视为绝对路径的开头。显然,您在该位置没有文件,/WEB-INF/config/prod.properties

如果您按照 this answer 中的建议使用 classpath: 前缀,那么您必须确保 /WEB-INF/config/prod.properties 位于类路径上。这是一个非常不常见的放在类路径上的东西,所以我不推荐它。

最后,正如您所发现的,您可以使用

@PropertySource("/WEB-INF/config/prod.properties")
// or to support your property
@PropertySource("${prodPropertiesFile}")

它将尝试通过ServletContext检索资源。它的 javadoc 指出

The path must begin with a / and is interpreted as relative to the current context root

您的 WEB-INF 文件夹将位于上下文根目录中(基本上是为 Servlet 容器选择的目录作为 Web 应用程序的根目录),因此将找到并使用资源。

<小时/>

您可以在官方文档here中阅读有关Resource的更多信息。 ,以及关于 ResourceLoader 进程,here .

关于java - 为什么Spring的PropertySource会抛出FileNotFoundException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40540605/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com