在spring/springboot中,使用静态方法时,如果需要从配置文件读取配置,利用@Value无法注入至静态变量中,例如以下代码并不会获取到需要的值。
@Value("${xyz.api.targetPath}")
static String targetPath1;
@Value("${xyz.api.directoryPath}")
static String directoryPath1;
这是由于依赖注入(Dependency Injection, DI)主要是面向Bean实例的。@Value注解也是基于Spring的依赖注入机制工作,它允许你将配置文件中的值注入到Bean的非静态字段或方法中。然而,Spring的依赖注入容器管理的是Bean的生命周期,包括实例化Bean、装配Bean的依赖关系等。静态变量不属于任何特定Bean实例的生命周期范畴,它们属于类级别,只有一份,且在类加载时就被初始化,这早于Spring容器初始化及依赖注入发生的时机。
因此,当你尝试直接在静态字段上使用@Value注解时,Spring的依赖注入机制无法作用于静态变量,因为它无法在类加载阶段对静态变量进行动态赋值。这就是为什么直接在静态变量上使用@Value注解无法从配置文件读取配置值的原因。
解决这一问题的方法,可以通过通过非静态初始化方法注入静态字段值的模式。如下:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @ClassName:
* @author: burouqing
* @Description:
* 通过方法参数,我们可以使用@Value注解来注入配置值,并直接设置到静态字段上。
* 这种方法应该能够解决您遇到的初始化问题,同时避免了IDE的编译错误提示。
* @Date: 2024-05-14 17:32:49
* @Version: 1.0.0
*/
@Component
public class DceConfig {
private static String targetPath;
private static String directoryPath;
@Autowired
public void initConfig(@Value("${xyz.api.targetPath}") String targetPath,
@Value("${xyz.api.directoryPath}") String directoryPath) {
DceConfig.targetPath = targetPath;
DceConfig.directoryPath = directoryPath;
}
public static String getTargetPath() {
return targetPath;
}
public static String getDirectoryPath() {
return directoryPath;
}
}
输出:
这样就可以很好的解决这个问题了!