guice injection in static variable

女生的网名这么多〃 提交于 2019-12-23 07:31:38

问题


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

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.

What is really happening here?


回答1:


Guice does not inject static fields by design. 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.

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

requestStaticInjection(Foo.class);

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

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.



来源:https://stackoverflow.com/questions/28513147/guice-injection-in-static-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!