java - 为什么 Spring Boot 的资源优先级会忽略我的外部属性文件?

标签 java spring spring-boot properties properties-file

作为 Spring Boot 项目的一部分,我需要加载某些属性文件,默认情况下,该文件位于 de src/main/resources 目录下。另外,我需要能够加载外部属性文件(位于项目的根目录)。如果此外部文件存在,则应将文件路径作为命令行属性传递。

文件结构如下:

/app_project
   Net.properties (external file)
   /src
      /main
         /resources
            Net.properties (default file)

问题是,除非您将外部文件的内容复制/覆盖到 /resources 目录下的文件中,否则使用这些属性的依赖项将不起作用。

已更新

到目前为止我已经尝试过:

  • 将文件作为外部资源加载并将其加载到 Properties 对象 ( https://docs.oracle.com/javase/7/docs/api/java/util/Properties.html )
  • 将属性另存为系统属性
  • 通过重写 addResourceHandlers() 以包含位置来修改资源处理程序以查看其他目录
  • 使用 -cp 参数在 CLASSPATH 中显式包含文件的位置(如 @veysiertekin 建议)
  • 将其加载为@PropertySource(按照@Nikolay Shevchenko的建议)
  • 使用 spring.config.location 覆盖 Spring Boot 的配置位置(按照 @gW​​ombat 的建议)

通过我尝试过的所有这些方法,文件确实被读取和加载,但在某些时候,应用程序每次都会求助于 src/main/resources 下的文件。

我怀疑这可能与文件的优先级有关(如此处所述 https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html ),但我只是无法弄清楚发生了什么。

预先感谢您的帮助。

最佳答案

尝试一下

@PropertySources({
        @PropertySource(name = "default", value = "classpath:default.properties"),
        @PropertySource(name = "external", value = "classpath:external.properties", ignoreResourceNotFound = true)
})
public class YourSpringBootApplication {
...
}

关于java - 为什么 Spring Boot 的资源优先级会忽略我的外部属性文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49072990/

相关文章:

java - Spring Boot 中是否有一个很好的 zalando-problem 实现示例?

java - 我的简单 Java 程序不断出现 "Cannot find symbol",但不知道为什么

java - 结束 JUnit 测试

java - spring boot data jpa连接不上mysql数据库

java - 在 Spring Boot 中通过 POST 创建对实体创建的父引用

java - 从 Spring Boot 自定义 validator 返回不同的 HTTP 状态代码

java - 如何在 Spring Boot 2 和 Activiti 7 中添加 Activiti Spring Boot Starter Basic?

java - 如何在 aem groovy 控制台中获取服务?

java - 当 a4j :commandLink and a4j:commandButton not working properly 时,Richfaces 4 和 JSF2.0 出现问题

java - Maven 应用程序组装器插件 : change current directory before launching program