Spring中如何为静态变量注入值

在 Spring 中,如果使用 @Value 注解注入值,不能将其应用于 static 字段。Spring 只能为实例变量注入值,不能直接对静态变量进行注入。

使用 @PostConstruct 初始化

如果确实需要在静态上下文中使用该值,可以使用 @PostConstruct 方法来设置静态变量:

java 复制代码
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class UserConfig {

    @Value("${upload.user}")
    private String user;

    private static String staticUser;

    @PostConstruct
    public void init() {
        staticUser = user;
    }

    public static String getStaticUser() {
        return staticUser;
    }
}

现在可以通过 UserConfig.getStaticUser() 来访问 upload.user 的值。

相关推荐
娃哈哈哈哈呀5 分钟前
html-pre标签
java·前端·html
LanLance7 分钟前
ES101系列09 | 运维、监控与性能优化
java·运维·后端·elasticsearch·云原生·性能优化·golang
Java永无止境8 分钟前
Web前端基础:HTML-CSS
java·前端·css·html·javaweb
clk66071 小时前
Spring Boot
java·spring boot·后端
扣丁梦想家1 小时前
✅ 常用 Java HTTP 客户端汇总及使用示例
java·开发语言·http
sss191s1 小时前
Java 集合面试题 PDF 及常见考点解析与备考指南
java·开发语言·pdf
七七&5561 小时前
java面试-场景题
java·python·面试
loser.loser1 小时前
QQ邮箱发送验证码(Springboot)
java·spring boot·mybatis
誰能久伴不乏2 小时前
Qt 开发中的父类与父对象的区别和父对象传递:如何选择 `QWidget` 或 `QObject`?
java·开发语言·qt
喜欢踢足球的老罗2 小时前
在Spring Boot 3.3中使用Druid数据源及其监控功能
java·spring boot·后端·druid