SpringBoot 中属性文件、YAML 文件和命令行参数之间的优先顺序

Precedence order among properties file, YAML file, and Command Line arguments in SpringBoot

在我的 Spring 应用程序中,我一直在使用 application.properties 文件。但最近我遇到了 application.yaml 个文件。三者的优先顺序是什么以及使用个体的优势(如果有的话)。

我知道这可能是个愚蠢的问题。但我对它们的用法感到困惑。

Spring引导属性解析属性命令描述here.

application.properties application.yaml 的使用不是预期的。使用一种格式或另一种格式,但不能同时使用两种格式。无论您使用哪个,都将按照 属性 优先顺序在位置 12 或 13(取决于文件是否打包在应用程序 JAR 中)处理。

在此处包括上述 link 的摘录以避免 link 腐烂 ...

Spring Boot uses a very particular PropertySource order that is designed to allow sensible overriding of values. Properties are considered in the following order:

  1. Devtools global settings properties on your home directory (~/.spring-boot-devtools.properties when devtools is active).
  2. @TestPropertySource annotations on your tests.
  3. @SpringBootTest#properties annotation attribute on your tests.
  4. Command line arguments.
  5. Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property)
  6. ServletConfig init parameters.
  7. ServletContext init parameters.
  8. JNDI attributes from java:comp/env.
  9. Java System properties (System.getProperties()).
  10. OS environment variables.
  11. A RandomValuePropertySource that only has properties in random.*.
  12. Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants)
  13. Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants)
  14. Application properties outside of your packaged jar (application.properties and YAML variants).
  15. Application properties packaged inside your jar (application.properties and YAML variants).
  16. @PropertySource annotations on your @Configuration classes.
  17. Default properties (specified using SpringApplication.setDefaultProperties).

简单来说,

如果你有 yaml 和属性文件,并且两者有相同的密钥,那么 spring 启动将首先在属性中查找,如果没有找到则转到 yaml。