Static Variable Injection

I have doubts about eye injections. Is it possible to enter the value of the @named variable in a static variable?

I tried

@Provides @Named("emp.id") public Integer getEmpId() { return 2; } 

and tried to enter this value into a static variable, for example

  @Inject @Named("emp.id") private static Integer id; 

But the id value returns null. When I removed the static modifier, the identifier gave the value 1.

What is really going on here?

+5
source share
2 answers

Guice does not introduce static fields by design. You can request a static injection , but this should only be done as a crutch :

This API is not recommended for general use because it suffers from many of the same problems as static factories: it is clumsy for testing, it makes errors opaque and relies on global state.

In your case, you can add this to your configure method so that your static field is entered by Guice:

 requestStaticInjection(Foo.class); 

If you do not add this, Integer will be initialized to zero (by default).

I have no idea why id was set to 1 after removing the static modifier. It seems that it should have been set to 2 if your Guice module was configured correctly.

+9
source

I think no. Injection works with an object, a static type variable.

0
source

Source: https://habr.com/ru/post/1213373/


All Articles