SpringBoot的@Value给静态变量注入application.properties属性值
作者:长安明月 时间:2023-09-20 11:54:07
一、问题描述
如果在 SpringBoot 项目中的 application.properties 配置了某个属性(假如属性名为 test.key),我们可以在 controller 层或 service 层使用 @Value 标签获取属性值,如下代码所示。
package com.test.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Value("${test.key}")
public String testKey;
}
也可以在一个 Java 文件中,打上 @Component 标签,再使用上述 @Value 标签,同样可以获取到配置文件中的属性值。
但是,如果项目中需要给静态变量注入配置文件中的属性值的话(也就是,给 static 修饰的变量做 @Value 注入),发现变量值为 null。示例代码如下所示。
@Value("${test.key}")
public static String testKey;
上述代码,静态变量并未成功注入值。
@Value 只能给普通变量做值注入。那么如何给静态变量做值注入呢?
二、解决方法
在类名上加 @Component 注解(如果 Java 文件是 controller 或 service 这些已经被 Spring 注入管理的类的话,则不需要再额外打该标签)使用 setXXX(abc) 方法,并在 setXXX(abc) 方法上加上 @Value 注解。如下代码示例。
package com.test.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class SignUtil {
public static String filepath = null;
@Value("${filepath}")
public void setFilePath(String filepath) {
log.info("静态变量 filepath 赋值:[{}]", filepath);
SignUtil.filepath = filepath;
}
}
备注:
如果是 IDEA 为静态变量生成的 set 方法,会在方法上带上 static 修饰符,这样是不行的,需要去掉 static 修饰符。
来源:https://blog.csdn.net/piaoranyuji/article/details/126955213
标签:SpringBoot,@Value,注入,属性值
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java实现画图 给图片底部添加文字标题
2023-03-28 23:23:06
![](https://img.aspxhome.com/file/2023/3/79823_0s.jpg)
深入探究Java线程的状态与生命周期
2021-10-01 17:44:10
![](https://img.aspxhome.com/file/2023/7/122957_0s.png)
Activiti如何启动流程并使流程前进
2023-11-18 18:38:51
![](https://img.aspxhome.com/file/2023/9/59489_0s.png)
如何用Java注解和反射实现依赖注入
2022-11-04 11:34:10
FFmpeg Principle分析Out put File 数据结构
2023-02-17 08:26:49
![](https://img.aspxhome.com/file/2023/5/139155_0s.jpg)
Gradle学习教程之部署上传项目详解
2023-08-08 20:46:46
Java调用WebService接口作测试
2023-08-11 17:00:20
![](https://img.aspxhome.com/file/2023/9/78279_0s.png)
RocketMQ特性Broker存储事务消息实现
2022-07-10 20:42:13
IDEA JetBrains Mono字体介绍和安装教程(详解)
2022-01-23 17:57:51
![](https://img.aspxhome.com/file/2023/5/120535_0s.jpg)
mybatis-plus使用问题小结
2023-10-30 06:45:58
学习使用Material Design控件(一)
2023-07-27 13:14:06
![](https://img.aspxhome.com/file/2023/3/84743_0s.jpg)
Struts2中Action中是否需要实现Execute方法
2021-10-30 06:57:23
Java中websocket消息推送的实现代码
2023-06-02 09:26:56
实例讲述Java IO文件复制
2023-01-30 17:25:32
Android实现画板、写字板功能(附源码下载)
2021-11-01 17:40:56
![](https://img.aspxhome.com/file/2023/4/111724_0s.jpg)
Spring数据访问模板化方法
2022-03-15 06:23:02
![](https://img.aspxhome.com/file/2023/0/129950_0s.png)
Java URL自定义私有网络协议
2021-08-11 02:21:06
![](https://img.aspxhome.com/file/2023/1/85871_0s.png)
深入理解Java中的接口
2023-11-08 23:52:43
轻松实现Rxjava定时器功能
2022-03-12 06:23:27
Java必备知识之位运算及常见进制解读
2022-02-10 00:42:19
![](https://img.aspxhome.com/file/2023/5/92715_0s.jpg)