@RefreshScope与@ConfigurationProperties对比

RefreshScope

@RefreshScope(org.springframework.cloud.context.scope.refresh)是spring cloud提供的一种特殊的scope实现,用来实现配置、实例热加载。

@RefreshScope 实现流程

  1. 需要动态刷新的类标注@RefreshScope 注解
  2. @RefreshScope 注解标注了@Scope 注解,并默认了ScopedProxyMode.TARGET_CLASS; 属性,此属性的功能就是在创建一个代理,在每次调用的时候都用它来调用GenericScope get 方法来获取对象
  3. 如属性发生变更会调用 ContextRefresher refresh() -》RefreshScope refreshAll() 进行缓存清理方法调用,并发送刷新事件通知 -》 GenericScope 真正的 清理方法destroy() 实现清理缓存
  4. 在下一次使用对象的时候,会调用GenericScope get(String name, ObjectFactory<?> objectFactory) 方法创建一个新的对象,并存入缓存中,此时新对象因为Spring 的装配机制就是新的属性了。

客户端项目增加依赖项

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

客户端项目修改配置文件

#显示的暴露接入点
management.endpoints.web.exposure.include=refresh,health,info

客户端程序增加支持刷新注解

@RestController
//刷新触发地址/actuator/refresh - post
@RefreshScope
public class ConfigTestController {

	//配置信息通过@Value注解读取,配置项用${配置项}读取
	@Value("${test.config}")
	private String configTest;

	@RequestMapping("/ConfigTest")
	public String ConfigTest(){
		return this.configTest;
	}
}

ConfigurationProperties

在 Spring Boot 项目中,为满足以上要求,我们将大量的参数配置在 application.properties 或 application.yml 文件中,通过 @ConfigurationProperties 注解,我们可以方便的获取这些参数值

test:
  auth:
    client:
      id: admin
      secret: admin123456
@Component
@ConfigurationProperties("test.auth.client")
@Getter
@Setter
public class AuthClientProp {

    /**
     * 授权id
     */
    private String id;
    /**
     *  授权密钥
     */
    private String secret;

}

启动时,id和secret会自动赋值为admin和admin123456。
通过发送post请求到http://服务ip:端口/actuator/refresh,会触发刷新机制,从通过配置中心从git库拉取最新的数据。而不需要添加注解@RefreshScope。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiegwei

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值