@value如何读取配置值至静态变量中?

在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;
    }
}

输出:

这样就可以很好的解决这个问题了!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不柔情

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值