java 静态变量中的guice注入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28513147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:43:23  来源:igfitidea点击:

guice injection in static variable

javaguiceguice-3

提问by Robin

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

我对guice注射有疑问。是否可以将@named 变量值注入静态变量?

I have tried

我努力了

@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;

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

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

What is really happening here?

这里到底发生了什么?

回答by condit

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

Guice 不会按设计注入静态字段。您可以请求静态注入,但这只能作为一个拐杖来完成

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.

不建议将此 API 用于一般用途,因为它与静态工厂存在许多相同的问题:测试笨拙,依赖项不透明,并且依赖于全局状态。

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

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

requestStaticInjection(Foo.class);

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

如果您不添加此项,则 Integer 将被初始化为 null(默认情况下)。

I have no idea why idwas 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.

但是,我不知道为什么id在删除静态修饰符后将其设置为 1。如果您的 Guice 模块设置正确,它似乎应该被设置为 2。