@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()方法可以获取最新的静态变量值。

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

相关推荐
间彧14 小时前
对比GraalVM Native Image与传统JVM,在内存管理方面各自适合哪些具体业务场景?
java
明洞日记14 小时前
【数据结构手册002】动态数组vector - 连续内存的艺术与科学
开发语言·数据结构·c++
福尔摩斯张14 小时前
《C 语言指针从入门到精通:全面笔记 + 实战习题深度解析》(超详细)
linux·运维·服务器·c语言·开发语言·c++·算法
daidaidaiyu14 小时前
Spring IOC 源码学习一 基本姿势
java·spring
间彧14 小时前
Spring AOT + GraalVM Native Image:云原生Java的效能引擎
spring
LSL666_14 小时前
SpringBoot自动配置类
java·spring boot·后端·自动配置类
甜鲸鱼15 小时前
Java与MySQL中的枚举(Enum)
java·mysql
xxxxxxllllllshi15 小时前
【LeetCode Hot100----14-贪心算法(01-05),包含多种方法,详细思路与代码,让你一篇文章看懂所有!】
java·数据结构·算法·leetcode·贪心算法
pengzhuofan15 小时前
Sentinel 服务保护
java·微服务·sentinel
6***379415 小时前
Java安全
java·开发语言·安全