Springboot @Value注入static属性

文章目录

概要

Spring 不直接支持对静态字段的注入,因为静态字段属于类级别,Spring 无法直接通过实例化 bean 的方式注入静态字段。不过你可以通过工厂方法来达到类似的效果。静态字段和静态方法的使用可能违背了 Spring 框架的设计理念,这种方式可能不是最佳实践。一般@Value是使用在非静态方法上的

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Test {
    @Value("${url}")
    public String url = "/dev/xx";
}

对于静态方法,以下做法是无效的

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Test {
    @Value("${url}")
    public static String url = "/dev/xx";
}

技术实现

静态字段注入

public class MyBean {
    private static String staticField;

    public static String getStaticField() {
        return staticField;
    }

    public static void setStaticField(String staticField) {
        MyBean.staticField = staticField;
    }
}

在 XML 配置中,通过 和 元素调用静态方法:

<bean class="com.example.MyBean" factory-method="setStaticField">
    <constructor-arg value="valueToSet" />
</bean>

使用set方法注入

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Test {
    public static String url = "/dev/xx";
    
    @Value("${url}")
    public static void setUrl(String url) {
        Test.url = url;
    }
}

通过中间变量赋值

import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Test {
    public static String url = "/dev/xx";
    @Value("${url}")
    public String tempUrl = "/dev/xx";
    @PostConstruct
    public void init() {
        url = tempUrl;
    }
}
  • @PostConstruct说明
    被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Serclet的inti()方法。被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

刀鋒偏冷

支持一发成植,一步修复发际

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

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

打赏作者

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

抵扣说明:

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

余额充值