spring 类路径在 WEB-INF/classes 下找不到配置文件

spring classpath could not find config file under WEB-INF/classes

我正在使用 Spring 启动并尝试使我的应用程序能够在 运行 时获取配置文件。这是我在 spring 文件

中的内容
<context:property-placeholder location="classpath:config.properties" />

但是我在启动服务时出现了这个错误

Could not load properties; nested exception is java.io.FileNotFoundException: class path resource [config.properties] cannot be opened because it does not exist

我试着改成

<context:property-placeholder location="classpath*:config.properties" />

我遇到了一个不同的错误

Could not resolve placeholder 'service.name' in string value "${service.name}"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'service.name' in string value "${service.name}"

看起来它可以找到文件但找不到字符串(在 config.properties 内)

我将 config.properties 放在路径 WEB-INF/classes/ 下,在 war 文件中

788 Mon Oct 19 09:54:28 PDT 2015 WEB-INF/classes/config.properties

有人知道哪里出了问题吗?

提前致谢!

WEB-INF/classes 是我希望在旧的 WAR 风格的应用程序而不是 Spring 启动应用程序中找到类路径资源的地方。您应该可以通过将 config.properties 放在 src/main/resources 中来解决您的问题,而不是 Maven 中的默认位置或 Gradle(这是非常流行的 Spring Boot 构建工具我怀疑你正在使用一个或另一个)。

其次-我建议不要自己配置配置的位置,只需使用 Spring 引导默认位置,即 src/main/resources/application.properties 在此查找配置文件location 是一种约定,无需进一步配置即可使用(除了删除当前的 属性 配置)。

请参考23.3 http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

SpringBoot 默认从类路径中查找 application.properties,你的类路径中有 application.properties 吗?如果是,请在 application.properties.

中声明一个 属性 spring.config.location=classpath:/config.properties

如果默认情况下没有 application.properties 文件,请在启动服务器时通过命令行参数传递配置的位置,如下所示。

$ java -jar myproject.jar --spring.config.location=classpath:/cofnig.properties

有关 spring 配置的更多信息,请参阅 SpringExternalizeConfig