概要
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()方法之前运行。