静态函数中@Value 注释的替代方法 [英] An alternative to @Value annotation in static function

查看:23
本文介绍了静态函数中@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).

所以你有两个选择:

  • (更好的)使字段非静态
  • (丑陋的 hack)添加一个写入静态字段的非静态 setter,并将 @Value 注释添加到 setter.
  • (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.
  • 然后是 MethodInvokingFactoryBean 的技巧 -- 这个例子是用于自动装配的字段,但我想你也可以为 @Value 调整它
  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆