SpringBoot的@Value给静态变量注入application.properties属性值
一、问题描述
如果在 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 修饰符。
到此这篇关于SpringBoot的@Value给静态变量注入application.properties属性值的文章就介绍到这了,更多相关SpringBoot的@Value注入属性值内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
spring boot @ResponseBody转换JSON 时 Date 类型处理方法【两种方法】
这篇文章主要介绍了spring boot @ResponseBody转换JSON 时 Date 类型处理方法,主要给大家介绍Jackson和FastJson两种方式,每一种方法给大家介绍的都非常详细,需要的朋友可以参考下2018-08-08
springboot整合ehcache 实现支付超时限制的方法
在线支付系统需要极高的稳定性,在有限的系统资源下,稳定性优先级要高于系统并发以及用户体验,因此需要合理的控制用户的支付请求。下面通过本文给大家介绍springboot整合ehcache 实现支付超时限制的方法,一起看看吧2018-01-01
spring boot security 没有合适的构造器问题
这篇文章主要介绍了spring boot security 没有合适的构造器问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2023-12-12


最新评论