静态函数中@Value注释的替代方法 [英] An alternative to @Value annotation in static function
本文介绍了静态函数中@Value注释的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
无法在静态变量上使用 @Value
。
It's not possible to use @Value
on a static variable.
@Value("${some.value}")
static private int someValue;
static public void useValue() {
System.out.println(someValue);
}
当我这样做时, 0
已打印。那么什么是一个很好的替代方案?
When I do this, 0
is printed. So what is a good alternative to this?
推荐答案
Spring注入静态字段(默认情况下)。
Spring inject noting in static field (by default).
所以你有两个选择:
- (更好的一个)使该字段非静态
- (丑陋的黑客)添加一个无静态的setter,它在静态字段中写入,并将
@Value
注释添加到setter。 / li>
- (the better one) make the field non static
- (the ugly hack) add an none static setter which writes in the static field, and add the
@Value
annotation to the setter.
- and then there is the trick with the MethodInvokingFactoryBean -- this example is for autowired fiels, but I guess you can adapt it for
@Value
too
这篇关于静态函数中@Value注释的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文