guice注入静态变量

Rob*_*bin 9 java guice guice-3

我对guice注射有疑问.是否可以将@named变量值注入静态变量?

我试过了

@Provides
@Named("emp.id")
public Integer getEmpId() {
   return 2;
}
Run Code Online (Sandbox Code Playgroud)

并试图将此值注入静态变量,如

 @Inject
 @Named("emp.id")
 private static Integer id;
Run Code Online (Sandbox Code Playgroud)

id返回值为null,当我删除静态修饰符时,id给出了值1.

这里到底发生了什么?

con*_*dit 14

Guice不会按设计注入静态字段.您可以请求静态注入,但这应该仅作为拐杖进行:

建议不要将此API用于一般用途,因为它遇到许多与静态工厂相同的问题:测试时笨拙,依赖性不透明,依赖于全局状态.

在您的情况下,您可以将此添加到您的configure方法,以让Guice注入您的静态字段:

requestStaticInjection(Foo.class);
Run Code Online (Sandbox Code Playgroud)

如果不添加此项,则Integer将初始化为null(默认情况下).

但是,我不知道为什么id在删除静态修改器后为什么设置为1.如果您的Guice模块设置正确,它似乎应该设置为2.