通常我们在application.properties中配置属性值,然后通过@Value在实例化的类中进行注入。比如application.properties中配置为:

server.url=127.0.0.1

那么在代码中使用如下方式便进行注入:

@Value("${server.url}")
private String serverUrl;

但如果某些属性我们想注入到静态变量上,比如定义了一个Constants的类,里面存储的都是static的变量,比如:

@Component
public class RongContants {

    /**
     * 应用AppKey
     */
    public static String appKey;

    public static String appSecret;

}

此时该如何处理呢?如果依旧使用@Value会发现无法正常注入,属性的值依旧是null。

此时我们需要对静态属性提供一个set方法,在set方法进行注入,就可解决该问题。

@Component
public class RongContants {

    /**
     * 应用AppKey
     */
    public static String appKey;

    public static String appSecret;

    @Value("${appKey}")
    public void setAppKey(String APP_KEY) {
        appKey = APP_KEY;
    }

    @Value("${appSecret}")
    public void setAppSecret(String APP_SECRET) {
        appSecret = APP_SECRET;
    }

}

由于属性是静态的,appKey和appSecret无法使用this进行区分,此时set方法中参数的变量最好与属性值进行区分。

其实,正常来说并不建议使用这种形式进行注入,因为提供了set方法之后,原本的静态变量有可能被改变了。而正常情况下我们的静态变量一般都是final形式的。

但如果你希望通过@Value形式进行注解,这是一种思路和方法。

精品SpringBoot 2.x视频教程

《Spring Boot 2.x 视频教程全家桶》,精品Spring Boot 2.x视频教程,打造一套最全的Spring Boot 2.x视频教程。



Spring Boot对静态变量@Value注入默认值插图

关注公众号:程序新视界,一个让你软实力、硬技术同步提升的平台

除非注明,否则均为程序新视界原创文章,转载必须以链接形式标明本文链接

本文链接:http://www.choupangxia.com/2020/05/30/spring-boot-value/