替代@Value静态功能注释 [英] An alternative to @Value annotation in static function

查看:187
本文介绍了替代@Value静态功能注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许这是不可能使用@Value批注的变量在静态函数是这样的:

Maybe it's not possible to use @Value annotated variable in static function like this:

@Value("${some.value}")
static private int someValue;

static public void useValue() {
    System.out.println(someValue);
}

当我这样做 0 印刷。那么,什么是好方法吗?

When I did this 0 was printed. So what is good alternative of that?

推荐答案

春季注射在静态字段指出(默认情况下)。

Spring inject noting in static field (by default).

所以,你有两种选择:


  • (最好的一个),使该字段非静态

  • (丑陋的黑客)添加无静态二传手它写在静态字段,以及 @Value 标注添加到引领者。

  • (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 <绝招/ A> - 这个例子是自动装配fiels,但我猜你能适应它 @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天全站免登陆