Spring Boot配置文件简介
简单介绍一下spring boot的配置文件吧,主要介绍一下配置文件的优先级以及配置文件的使用(ps:重点看3、4点吧),后面我会写一篇关于配置文件的源码分析文章,今天就先给大家热一下身,自己今天也摸一下鱼,嘿嘿!!!
-
自动加载: Spring Boot会自动加载默认的配置文件。对于properties文件,Spring Boot会默认加载
application.properties
文件;对于YAML文件,Spring Boot会默认加载application.yml
或application.yaml
文件。这些文件可以放置在classpath下的/config
目录或者与jar包同级目录,统计目录的config,以及config下面的直接子目录。 -
多环境配置: Spring Boot支持基于不同环境的配置文件。通过使用
spring.profiles.active
属性,可以指定当前活动的配置文件环境。例如,可以创建application-dev.properties
或application-dev.yml
文件,用于开发环境的配置。Spring Boot会根据spring.profiles.active
的值自动加载相应的配置文件。 -
属性优先级: 在Spring Boot中,属性的优先级由高到低依次为:命令行参数 > 系统属性 > 环境变量 > 配置文件中的属性。这意味着可以通过命令行参数、环境变量或系统属性来覆盖配置文件中的属性值。
官方文档描述, 后面的属性源可以覆盖前面定义的值。按以下顺序考虑来源:
- Default properties (specified by setting SpringApplication.setDefaultProperties).
- @PropertySource annotations on your @Configuration classes. Please note that such property sources are not added to the Environment until the application context is being refreshed. This is too late to configure certain properties such as logging.* and spring.main.* which are read before refresh begins.
-
Config data (such as application.properties files).
(配置文件) - A RandomValuePropertySource that has properties only in random.*.
-
OS environment variables.
(环境变量) - Java System properties (System.getProperties()).(java系统属性)
- JNDI attributes from java:comp/env.
- ServletContext init parameters.
- ServletConfig init parameters.
- Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property).
-
Command line arguments.
(命令行参数) - properties attribute on your tests. Available on @SpringBootTest and the test annotations for testing a particular slice of your application.
- @DynamicPropertySource annotations in your tests
- @TestPropertySource annotations on your tests.
- Devtools global settings properties in the $HOME/.config/spring-boot directory when devtools is active.
-
配置文件加载顺序: Spring Boot会按照一定的顺序加载配置文件。首先,会加载默认的配置文件,然后根据
spring.profiles.active
加载对应的环境配置文件。最后,会加载其他的外部化配置文件。首先加载jar包内的配置文件(yml、properties同时存在会使用properties),再加载外部配置文件,后加载的配置覆盖先加载的文件。
配置文件加载顺序如下:后面的配置覆盖前面的配置(ps: 外部配置覆盖内部配置,同级目录config下面的覆盖外面的)。- classPath下面配置
- classpathc下面config文件夹下面的配置
- jar包所在路劲的配置
- jar包所在路劲config下的配置
eg:应用会使用config下面的properties
-
属性注入: Spring Boot支持将配置文件中的属性值注入到应用程序中的Bean中。通过使用
@Value
注解或@ConfigurationProperties
注解,可以将属性值注入到相应的字段或方法参数中。@Value
注解适用于单个属性的注入,而@ConfigurationProperties
注解适用于将一组属性值注入到一个自定义的配置类中。 -
配置文件解析: Spring Boot使用不同的解析器来解析不同类型的配置文件。对于properties文件,Spring Boot使用
PropertiesLoaderUtils
来解析文件内容;对于YAML文件,Spring Boot使用SnakeYAML库来解析文件内容。
配置文件相关的详细知识可以参考官网:https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config.files
配置文件加载流程参考:https://editor.csdn.net/md/?articleId=135341539