我在 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.yml
和 config/application.prod.yml
并且仍然保留 config/application.yml
? (包含默认属性,包括 spring.application.name
)
我读到配置是按这个顺序加载的,
- 当前目录的/config 子目录。
- 当前目录
- 类路径/配置包
- 类路径根
因此,我尝试从 /opt/apache-tomcat/lib
加载配置文件,但无济于事。
到目前为止什么有效
通过export CATALINA_OPTS="-Dspring.config.location=/opt/apache-tomcat/lib/application.dev.yml"
加载
但是我想知道的是,
- 找出为什么通过
/opt/apache-tomcat/lib
类路径加载不起作用。 - 有没有更好的方法来实现这一点?
最佳答案
您对加载顺序的看法是正确的。根据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/配置
它将被加载。
- 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
.
但我不建议使用这种方法。
- 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.yml
和 application.yml
文件,特定于配置文件的配置将覆盖默认配置。
我建议添加-Dspring.profiles.active=dev
(或prod
)to CATALINA_OPTS
在每个相应的服务器/tomcat 实例上。
关于spring-boot - 使用外部配置在 Tomcat 上进行 Spring 启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42429708/