spring boot 配置顺序

PropertySource顺序

Spring Boot使用PropertySource接口来表示配置属性的来源。并且允许属性值的覆盖,在较晚的PropertySource中定义的属性值可以覆盖较早的PropertySource中定义的属性值。PropertySource的顺序如下:

  1. Default properties (通过SpringApplication.setDefaultProperties(Map)设置).

  2. @PropertySource annotations on your @Configuration classes. 该配置源在refreshed阶段才会进入application context。这对于某些配置属性来说太迟了,例如logging.* 和 spring.main.*,这些属性在refresh阶段之前被读取。

  3. Config data (such as application.properties files).

  4. A RandomValuePropertySource that has properties only in random.*.

  5. 操作系统系统环境变量

  6. Java系统变量 (System.getProperties()).

  7. JNDI attributes from java:comp/env.

  8. ServletContext init parameters.

  9. ServletConfig init parameters.

  10. Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property).

  11. 命令行参数 (例如:--server.port=5820)

  12. properties attribute on your tests. Available on @SpringBootTest and the test annotations for testing a particular slice of your application.

  13. @DynamicPropertySource annotations in your tests.

  14. @TestPropertySource annotations on your tests.

  15. Devtools global settings properties in the $HOME/.config/spring-boot directory when devtools is active.

有多个配置文件时,配置的优先级如何?

  • 指定profile的配置文件会覆盖application.yaml;
  • 如果指定多个profile,则最后一个profile中的属性覆盖之前的profile;
    例如:指定spring.profiles.active=dev,hsqldb
    hsqldb.yaml覆盖application-dev.yaml和application.yaml中的配置;
    spring.profiles.active中指定的参数会被解析成application-{profile};
posted @ 2025-02-10 18:34  Hekk丶  阅读(28)  评论(0)    收藏  举报