@Value 注入 static 属性

本文将介绍怎样利用 @Value 注入 static 属性。

Spring 中,@Value 注解一般使用在非静态方法上的。如下:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Test {
    @Value("${jdbc.driver}")
    public String driver;
    
    @Value("${jdbc.url}")
    public String url;
}

如果将 @Value 注解用于静态方法,以下做法是无效的:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Test {
    @Value("${jdbc.driver}")
    public static String driver;
    
    @Value("${jdbc.url}")
    public static String url;
}

如果我们非要使用 @Value 注解将值注入到静态属性呢,可以使用下面方法:

方法一:使用 Spring 的 XML 配置文件,通过 Bean 注入,这里不做多讲解;

方式二:使用 setter 方法注入,如下:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Test {
    public static String url = "/dev/xx";
    @Value("${jdbc.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 = "";
    
    @Value("${jdbc.url}")
    public String tempUrl = "";
    
    @PostConstruct
    public void init() {
        url = tempUrl;
    }
}

上面实例中,@PostConstruct 和 @PreConstruct 作用如下:

  • @PostConstruct:被 @PostConstruct 注解修饰的方法会在服务器加载 Servlet 的时候运行,并且只会被服务器调用一次,类似于 Serclet 的 inti() 方法。被 @PostConstruct 修饰的方法会在构造函数之后,init() 方法之前运行。

  • @PreConstruct:被 @PreConstruct 修饰的方法会在服务器卸载 Servlet 的时候运行,并且只会被服务器调用一次,类似于 Servlet 的 destroy() 方法。被 @PreConstruct 修饰的方法会在 destroy() 方法之后运行,在 Servlet 被彻底卸载之前。

不傲才以骄人,不以宠而作威。——诸葛亮
0 不喜欢
说说我的看法 -
全部评论(
没有评论
关于
本网站专注于 Java、数据库(MySQL、Oracle)、Linux、软件架构及大数据等多领域技术知识分享。涵盖丰富的原创与精选技术文章,助力技术传播与交流。无论是技术新手渴望入门,还是资深开发者寻求进阶,这里都能为您提供深度见解与实用经验,让复杂编码变得轻松易懂,携手共赴技术提升新高度。如有侵权,请来信告知:hxstrive@outlook.com
公众号