【SpringBoot 属性加载机制】

SpringBoot 属性加载

一个 SpringBoot 应用的配置属性可以有多种不同的来源, 比如可以来自操作系统的环境变量, 比如可以来自 application.yaml 文件; 每一种不同的属性来源, 都会被 SpringBoot 封装成一个PropertySource对象, 保存在 Environment 对象的 PropertySources 类型成员的 propertySourceList 中;
在这里插入图片描述
一个PropertySource对象中就通过一个 Map 保存了这个属性源下的所有属性配置;

例如application.yaml文件中的配置会被保存到一个OrginTrackedMapPropertySource对象中;
在这里插入图片描述
这些属性源在 List 中的顺序决定了他们的优先级;

因为无论是通过@Value注解还是 @ConfigurationProperties 注解去获取属性值, 其本质都是调用了 Environment::getProperty方法; 具体获取的过程下面会讲到;

而这个方法的逻辑是顺序遍历所有属性源, 在遍历到的属性源中尝试去获取指定的属性, 如果找到了就直接返回; 所以在propertySourceList中越靠前, 属性源的优先级就越高;

SpringApplicationrun 方法内, prepareContext 之前, 先调用prepareEnvironment方法, 准备应用环境,加载各种属性源, 包括系统变量,环境变量,命令行参数,默认变量, 配置文件等;

不了解SpringBoot启动过程看这篇文章 http://t.csdnimg.cn/qqs6G

在这里插入图片描述

属性源优先级

优先级从高到低

  1. Nacos 配置中心的配置;
  2. 当前应用的命名行参数;
  3. JAVA 的系统属性, 也就是来自JVM的启动时给的参数;
  4. 操作系统的环境变量;
  5. application-xxx.yaml, 例如 application-dev.yaml
  6. application.yaml
  7. boostrap.yaml
  8. @PropertySource 注解指定的配置文件;
  9. 默认属性

SpringBoot官网对优先级的描述:

Spring Boot uses a very particular order that is designed to allow sensible overriding of values. Later property sources can override the values defined in earlier ones. Sources are considered in the following order:PropertySource

  1. Default properties (specified by setting ).SpringApplication.setDefaultProperties
  2. @PropertySource annotations on your classes. Please note that such property sources are not added to the until the application context is being refreshed. This is too late to configure certain properties such as and which are read before refresh begins.
  3. Config data (such as files).application.properties
  4. A that has properties only in .RandomValuePropertySource``random.*
  5. OS environment variables.
  6. Java System properties ().System.getProperties()
  7. JNDI attributes from .java:comp/env
  8. ServletContext init parameters.
  9. ServletConfig init parameters.
  10. Properties from (inline JSON embedded in an environment variable or system property).SPRING_APPLICATION_JSON
  11. Command line arguments.
  12. properties attribute on your tests. Available on @SpringBootTest and the test annotations for testing a particular slice of your application.
  13. @TestPropertySource annotations on your tests.
  14. Devtools global settings properties in the directory when devtools is active.$HOME/.config/spring-boot

举例 : @Value 注解

my:
  addr: localhost:7770
@Value("${my.addr}")
String addr;

总结来说是通过 BeanPostProcessor, 在 Bean 实例化以后, 调用 Environment::getProperoty 获取属性值, 然后通过反射注入到 bean 中;

@Value 注解的详细分析参考这篇文章

@Autowired 与 @Value 作用原理详解

  • 11
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值