静态变量中的guice注入

guice injection in static variable

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

我试过了

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

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

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

但是 id return 值为 null,当我删除静态修饰符时,id 的值为 1。

这里到底发生了什么?

Guice 没有设计注入静态字段。你可以 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.

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

requestStaticInjection(Foo.class);

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

不过,我不知道为什么 id 在您删除静态修饰符后设置为 1。如果您的 Guice 模块设置正确,它似乎应该设置为 2。