guice injection in static variable

2019-06-16 10:32发布

问题:

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.