springboot中static变量使用配置文件的值的方法

一、前言

springboot项目中,有时候需要让static变量使用properties/yml文件中配置的值。

此时,因为是静态变量,所以@Value注解无法直接使用。

虽然也可以在静态方法中直接读取properties/yml文件,然后给静态变量赋值;但是这样写总是比较繁琐,还有可能把properties/yml文件的路径搞错,十分不方便。

下面总结一些简单的方法。

二、实现InitializingBean接口

package com.others.utils;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;


@Configuration
public class StaticPropertiesUtil implements InitializingBean {

    public static Integer staticPort;

    @Value("${port.socket}")
    public Integer port;

    @Override
    public void afterPropertiesSet() throws Exception {
        staticPort = this.port;
    }
}

三、使用@PostConstruct注解

package com.others.utils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;


@Configuration
public class StaticPropertiesUtil {

    public static Integer staticPort;

    @Value("${port.socket}")
    public Integer port;

    @PostConstruct
    public void setStaticPort() {
        staticPort = this.port;
    }
}

四、总结

1.上面的方法,都是先用@Value注解读取到配置文件中的值,然后重写afterPropertiesSet方法、或者用@PostConstruct注解,在spring加载到某一步骤时调用这些方法给static变量赋值

2.因此,使用static变量时,不能太早,太早的话会为空;最好等待spring加载完成后、再使用static变量。

3.如果必须在spring加载完成前使用static变量、同时要求static变量读取配置文件中的值、那么可以自己写静态方法直接读取配置文件、给static变量赋值、然后使用。

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

追逐梦想永不停

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

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

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

打赏作者

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

抵扣说明:

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

余额充值