简体   繁体   English

guice注入静态变量

[英]guice injection in static variable

I Have doubt about guice injection. 我对guice注射有疑问。 Is it possible to inject a @named variable value to a static variable? 是否可以将@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 id return value null, When I removed static modifier the id gave value 1. 但是id返回值为null,当我删除static modifier时,id给出了值1。

What is really happening here? 这里到底发生了什么?

Guice does not inject static fields by design. Guice不会按设计注入静态字段。 You can request static injection but this should be done only as a crutch : 您可以请求静态注入,但这应该仅作为拐杖进行

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 configure method 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 id was set to 1 after you removed the static modifier, however. 但是,我不知道为什么在删除static修饰符后id被设置为1。 Seems that it should have been set to 2 if your Guice module was setup correctly. 如果您的Guice模块设置正确,它似乎应该设置为2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM