简体   繁体   中英

guice injection in static variable

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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