Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 626
Robin Avatar asked Feb 14 '15 06:02

Robin


People also ask

How do you inject static fields in Guice?

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.

What is @inject in Guice?

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.

How do you inject a Guice class?

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.

How does field injection work in Guice?

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.


1 Answers

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.

like image 165
condit Avatar answered Oct 30 '22 17:10

condit