且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

静态变量中的Guice注入

更新时间:2023-12-03 16:00:46

Guice并非根据设计注入静态字段.您可以请求静态注入,但是这只能通过拐杖:

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

不建议将该API用于一般用途,因为它会遇到许多与静态工厂相同的问题:它笨拙地进行测试,使依赖项变得不透明,并且依赖于全局状态.

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注入您的静态字段:

In your case you could add this to your configure method to have your static field injected by Guice:

requestStaticInjection(Foo.class);

如果您不添加此内容,则整数将被初始化为null(默认情况下).

If you don't add this the Integer will be initialized to null (by default).

我不知道为什么在删除static修饰符后将id设置为1.如果您的Guice模块设置正确,似乎应该将其设置为2.

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.