一、问题描述
如果在 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 修饰符。