spring-boot - 使用外部配置在 Tomcat 上进行 Spring 启动

标签 spring-boot configuration war tomcat8

我在 stackoverflow 上找不到这个问题的答案,因此我在这里提问,这样我可以得到一些想法。

我有一个 Spring Boot 应用程序,我已将其作为 war 包部署在 Tomcat 8 上。我遵循了本指南 Create a deployable war file这似乎工作得很好。

但是,我目前遇到的问题是能够将配置外部化,以便我可以将配置作为人偶模板进行管理。

在项目中我有的是,

src/main/resources
                  -- config/application.yml
                  -- config/application.dev.yml
                  -- config/application.prod.yml
                  -- logback-spring.yml

那么我怎样才能在外部加载 config/application.dev.ymlconfig/application.prod.yml 并且仍然保留 config/application.yml ? (包含默认属性,包括 spring.application.name)

我读到配置是按这个顺序加载的,

  1. 当前目录的/config 子目录。
  2. 当前目录
  3. 类路径/配置包
  4. 类路径根

因此,我尝试从 /opt/apache-tomcat/lib 加载配置文件,但无济于事。

到目前为止什么有效

通过export CATALINA_OPTS="-Dspring.config.location=/opt/apache-tomcat/lib/application.dev.yml"加载

但是我想知道的是

  1. 找出为什么通过 /opt/apache-tomcat/lib 类路径加载不起作用。
  2. 有没有更好的方法来实现这一点?

最佳答案

您对加载顺序的看法是正确的。根据Spring boot documentation

SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment:

  • A /config subdirectory of the current directory.
  • The current directory
  • A classpath /config package
  • The classpath root

The list is ordered by precedence (properties defined in locations higher in the list override those defined in lower locations).

[Note]
You can also use YAML ('.yml') files as an alternative to '.properties'.

这意味着如果您将 application.yml 文件放在 /opt/apache-tomcat/lib/opt/apache-tomcat/lib/配置 它将被加载。

  1. Find out why loading via /opt/apache-tomcat/lib classpath doesn't work.

但是,如果您将 application.dev.yml 放置到该路径,它将不会被加载,因为 application.dev.yml 不是 Spring 正在寻找的文件名。如果您希望 Spring 也读取该文件,则需要将其作为选项提供
--spring.config.name=application.dev-Dspring.config.name=application.dev.
但我不建议使用这种方法

  1. And is there a better method to achieve this ?

是的。使用 Spring profile-specific properties .您可以将文件从 application.dev.yml 重命名为 application-dev.yml,并提供 -Dspring.profiles.active=dev 选项. Spring 将读取 application-dev.ymlapplication.yml 文件,特定于配置文件的配置将覆盖默认配置。

我建议添加-Dspring.profiles.active=dev(或prod)to CATALINA_OPTS在每个相应的服务器/tomcat 实例上。

关于spring-boot - 使用外部配置在 Tomcat 上进行 Spring 启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42429708/

相关文章:

java - 使用 Spring Boot 在单个 PDF 中渲染表格和图表

tomcat - 无法通过 .ebextensions 文件更改 AWS 中的 tomcat 配置

java - ant 运行时出现 NoClassDefFoundError

gradle - Gradle创建的 war 文件中缺少Vaadin依赖项

java - Spring 测试主线程陷入应用程序的无限循环

java - kafka消费者组线程的线程顺序在每次启动时都不同

java - 如何在 Spring Integration 中动态添加队列以进行交换

基于 Java 的基于 Ehcache 的缓存配置不起作用

java - 在tomcat中手动解包 war 的问题

database - 手动安装 Jasper WAR 文件