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.
|
|
|
|
# @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数据来源
|
|
|
|
|
重点1:org.springframework.core.env.PropertySource,这是spring提供的配置源,里面包含了kv配置信息,其内部方法通过name获取对应的配置信息
|
|
|
|
|
![[Snipaste_2023-02-16_16-04-16 7.png]]
|
|
|
|
|
|
|
|
|
|
重点2:spring管理环境变量的接口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
|