且构网

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

如何吉斯填充字段批注

更新时间:2022-12-31 15:50:31

这吉斯接近这个问题的方法是,它只会填充这是本身吉斯 创建一个实例的领域的 1 。喷油器,创建实例后,可以使用反射API来看看类的字段,并检查他们的注释Field.getDeclaredAnnotations()$c$c>.

The way that Guice approaches this is that it will only populate the fields of an instance that was itself created by Guice1. The injector, after creating the instance, can use the Reflection API to look at the fields of the Class and inspect their annotations with Field.getDeclaredAnnotations().

这也是为什么,当你希望注入静态字段,你需要使用的原因Binder.requestStaticInjection()$c$c>填充静态字段。

This is also the reason why, when you want to inject into a static field, you need to use Binder.requestStaticInjection() to populate the static fields.

吉斯并不简单地扫描您的code的注释;所有注射从明确请求递归(例如 requestStaticInjection() Injector.getInstance()等)。现在往往是最初的,明确要求将某些库code已经作出。

Guice does not simply scan your code for annotations; all injections recurse from an explicit request (e.g. requestStaticInjection(), Injector.getInstance(), etc). Now often that initial, explicit request will have been made in some library code.

例如,如果你使用吉斯-的servlet 你让吉斯通过创建你的servlet实例服务();与()调用。但是,如果你没有这样做,在你的的web.xml ,而不是离开你的servlet配置,吉斯不会注入到servlet。

For example, if you're using guice-servlet you let Guice create the instances of your servlet by using the serve().with() calls. But if you didn't do that, and instead left your servlet config in your web.xml, Guice would not inject into your servlet.

1 - 你也可以要求使用显式注入 Binder.requestInjection()