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.
Dependency Injection for Java Developers with Dagger & Guice Injection is a process of injecting dependeny into an object. Method injection is used to set value object as dependency to the object. See the example below.
Client Application We need to create Injector object using Guice class createInjector() method where we pass our injector class implementation object. Then we use injector to initialize our consumer class. If we run above class, it will produce following output.
Field injection in the context of DI means that we annotate the fields of a class with the @Inject annotation, which tells Guice to inject the dependency directly into the class. We can also then remove them from the constructor, since we won't be calling the constructor at all.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With