@RefreshScope静态变量注入

@RefreshScope注解通常用于注入实例变量,而不是静态变量。由于静态变量与类直接关联,刷新操作无法直接影响它们。

如果你需要动态刷新静态变量的值,一种可行的方案是使用一个通过@Value注解注入的实例变量,并在该实例变量的getter方法中返回静态变量的值。这样,在实例变量更新时,可以通过调用getter方法来获取最新的静态变量值。

以下是示例代码:

import org.springframework.beans.factory.annotation.Value;

import org.springframework.cloud.context.config.annotation.RefreshScope;

import org.springframework.stereotype.Component;

@Component

@RefreshScope

public class StaticConfig {

private static String myStaticVariable;

@Value("${my.property.key}")

private void setMyStaticVariable(String value) {

myStaticVariable = value;

}

public static String getMyStaticVariable() {

return myStaticVariable;

}

}

在上述示例中,setMyStaticVariable()方法使用@Value注解将配置文件中的值注入到myStaticVariable实例变量中。然后,在getMyStaticVariable()方法中,直接返回静态变量的值。

当应用程序接收到刷新请求时(通过Actuator的刷新端点或其他方式),@RefreshScope注解会重新创建StaticConfig的实例,并通过setMyStaticVariable()方法注入最新的配置值。通过调用getMyStaticVariable()方法可以获取最新的静态变量值。

请注意,由于静态变量的生命周期与应用程序的生命周期相同,所以在应用程序启动时会初始化并保持不变,后续配置文件的更改不会自动更新已注入的静态变量值。因此,你仍然需要通过其他方式(如触发刷新操作)来更新静态变量的值。

相关推荐
松涛和鸣2 小时前
22、双向链表作业实现与GDB调试实战
c语言·开发语言·网络·数据结构·链表·排序算法
h***04774 小时前
SpringBoot(7)-Swagger
java·spring boot·后端
v***91305 小时前
Spring boot创建时常用的依赖
java·spring boot·后端
xlq223228 小时前
22.多态(上)
开发语言·c++·算法
666HZ6668 小时前
C语言——高精度加法
c语言·开发语言·算法
代码or搬砖8 小时前
MyBatisPlus讲解(二)
java·mybatis
星释8 小时前
Rust 练习册 100:音乐音阶生成器
开发语言·后端·rust
lcu1118 小时前
Java 学习42:抽象
java
Mr.朱鹏8 小时前
RocketMQ安装与部署指南
java·数据库·spring·oracle·maven·rocketmq·seata
雨中飘荡的记忆8 小时前
Spring表达式详解:SpEL从入门到实战
java·spring