静态变量中的Guice注入 [英] guice injection in static variable

查看:121
本文介绍了静态变量中的Guice注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对吉塞注射有疑问. 可以将@named变量值注入静态变量吗?

I Have doubt about guice injection. Is it possible to inject a @named variable value to a static variable?

我尝试过

@Provides
@Named("emp.id")
public Integer getEmpId() {
   return 2;
}

并尝试将此值注入静态变量,例如

and tried to inject this value to static variable such as

 @Inject
 @Named("emp.id")
 private static Integer id;

但是id返回值为null,当我删除静态修饰符时,id的值为1.

But the id return value null, When I removed static modifier the id gave value 1.

这里真正发生了什么?

推荐答案

Guice并非根据设计注入静态字段.您可以请求静态注入,但是这只能通过拐杖:

Guice does not inject static fields by design. You can request static injection but this should be done only as a crutch:

不建议将该API用于一般用途,因为它会遇到许多与静态工厂相同的问题:它笨拙地进行测试,使依赖项变得不透明,并且依赖于全局状态.

This API is not recommended for general use because it suffers many of the same problems as static factories: it's clumsy to test, it makes dependencies opaque, and it relies on global state.

在您的情况下,您可以将其添加到您的configure方法中,以让Guice注入您的静态字段:

In your case you could add this to your configure method to have your static field injected by Guice:

requestStaticInjection(Foo.class);

如果您不添加此内容,则整数将被初始化为null(默认情况下).

If you don't add this the Integer will be initialized to null (by default).

我不知道为什么在删除static修饰符后将id设置为1.如果您的Guice模块设置正确,似乎应该将其设置为2.

I have no idea why id was set to 1 after you removed the static modifier, however. Seems that it should have been set to 2 if your Guice module was setup correctly.

这篇关于静态变量中的Guice注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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