【问题标题】:Spring Boot - Loading a .properties file from WEB-INF/ folderSpring Boot - 从 WEB-INF/ 文件夹加载 .properties 文件
【发布时间】:2016-07-07 10:30:37
【问题描述】:

我有一个 Spring Boot 1.3 应用程序(部署为 .war),它需要能够从以下位置读取 .properties 文件:

WEB-INF/application.properties(在类路径之外,但相对于应用根文件夹)

...相对于:

WEB-INF/classes/application.properties(在类路径中,自动加载)

在 Spring Boot 1.3 中起作用的是以下 @PropertySource 注释:

@SpringBootApplication
@PropertySource(value = {"WEB-INF/application.properties"})
public class MyApplication {
        public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

它正确地获取了相对于应用根目录的.properties 文件。但是,在更新到 Spring Boot 1.4.0.RC1 后,这将停止工作。

从那时起,我尝试了以下方法:

@PropertySource("classpath:../application.properties")
@PropertySource("file:WEB-INF/application.properties")

还有

spring.config.location=classpath:../
spring.config.location=file:src/main/webapp/WEB-INF/
spring.config.location=WEB-INF/application.properties

但加载 .properties 时运气不佳。

我通常会将.properties 文件放在类路径中,但在这种情况下,由于我们的部署在远程位置上工作的方式,这不是一个选项。

我也不想使用绝对路径,因为要支持多个客户将是一场噩梦。

编辑:为了清楚起见 - 我想阅读的 .properties 不在 JAR(在我的情况下 - WAR)文件之外,而是在内部 - 只是不在类路径上,而是直接在 @ 987654333@ 通常其他资源(页面、图像)所在的文件夹。

【问题讨论】:

标签: spring-mvc spring-boot


【解决方案1】:

正如我在重复的 SO 问题中提到的:

将此行放入您的application.properties

logging.config=file:log4j.xml

第二个选项是将系统变量传递给-Dlogging.config=file:log4j.xml

在这种情况下,它应该位于 JAR 文件之外的当前目录中。

对评论的反应

如果您使用的是 WAR 文件,则根本不会使用您的主类。所以 PropertySource 注释在那里没有任何作用。

【讨论】:

  • 如问题所述,我想阅读的.properties 不在 JAR(在我的情况下为 WAR)文件之外,而是在内部。
【解决方案2】:

如果.properties 打包在.war 文件中。那你可以试试下面的方法(假设WEB-INF目录位于.war文件的根目录下。

@PropertySource("classpath:/WEB-INF/conf/application.properties")

【讨论】:

  • 谢谢,试过了,还是报错:class path resource [WEB-INF/conf/application.properties] cannot be opened because it does not exist
【解决方案3】:

原来这个问题是由 Spring Boot 1.4.0.RC1 中的 SpringBootTestContextBootstrapper 的错误引起的:https://github.com/spring-projects/spring-boot/issues/6371

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 2019-02-26
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 2013-03-02
    • 2020-12-02
    相关资源
    最近更新 更多