You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
obsidian-sync/日常学习/spring/spring/@PropertySource、@Value注解及动态...

43 lines
2.0 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# @Value
用途spring提取@value注解用于获取配置信息并绑定到变量
## 一、使用步骤
1. 使用@PropertySource注解引入配置文件
![[Snipaste_2023-02-16_16-04-16 5.png]]
![[Snipaste_2023-02-16_16-04-16 6.png]]
2. 使用@Value注解引用配置文件
![[Snipaste_2023-02-17_09-54-15.png]]
## 二、@Value数据来源
重点1org.springframework.core.env.PropertySource这是spring提供的配置源里面包含了kv配置信息其内部方法通过name获取对应的配置信息
![[Snipaste_2023-02-16_16-04-16 7.png]]
重点2spring管理环境变量的接口org.springframework.core.env.Environment
接口中的方法
![[Snipaste_2023-02-17_10-04-07.png]]
重点3解析@Value的过程
1. 将@Value注解的value参数值作为Environment.resolvePlaceholders方法参数进行解析
2. Environment内部会访问MutablePropertySources来解析
3. MutablePropertySources内部有多个PropertySource此时会遍历PropertySource列表调用
PropertySource.getProperty方法来解析key对应的值
重点4如果想改变@Value数据的来源只需要将配置信息包装为PropertySource对象放到Environment中的MutablePropertySources就行
### 例:从数据库获取配置
![[Snipaste_2023-02-17_10-04-07 1.png]]
![[Snipaste_2023-02-17_10-04-07 2.png]]
![[Snipaste_2023-02-17_10-04-07 3.png]]
## 实现@Value动态刷新
在springboot中使用@RefreshScope就可以
![[Snipaste_2023-02-17_10-04-07 5.png]]
在springmvc中需要通过自定义bean作用域实现
### 自定义bean作用域
![[Snipaste_2023-02-17_10-04-07 4.png]]
当@Scope中proxyMode为TARGET_CLASS的时候会给当前创建的bean通过cglib生成一个代理对象通过这个代理对象来访问目标bean对象。
### 思路
以实现一个自定义的Scope这个自定义的Scope支持@Value注解自动刷新需要使用@Value注解自动刷新的类上面可以标注这个自定义的注解当配置修改的时候调用这些bean的任意方法的时候就让spring重启初始化一下这个bean