guice 向哪些类注入对象?

发布于 2024-12-03 08:52:24 字数 131 浏览 1 评论 0原文

也许是一个愚蠢的问题,但是......我有一堆代码库,其中包含带有 @Inject 注释的类。但是当应用程序运行时,并非所有对象都被注入,有些值为空。

所以我的问题是:guice 如何知道必须处理哪些类?它是否以某种方式遍历对象图?

Maybe a stupid question, but... I've got a bunch of codebase with classes having @Inject annotations in it. But when the app runs not all objects get injected, some values are null.

So my question is: how does guice know which classes must be processed? Does it traverse object graph somehow?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

放肆 2024-12-10 08:52:24

虽然问题不是很清楚,但我会尝试澄清一些会发生或不会发生注入的情况,这样你就可以看到你可能面临什么问题:

  1. 如果类 A 有 @Inject 字段、构造函数或方法,但是 通常不会被注入。

  2. 实际上,在上述情况下,如果通过调用 injectMembers() 将实例显式“标记”为要在 Module 中注入,则可能会发生注入。

  3. 如果类 A 具有 @Inject 字段、构造函数或方法,并且它是由 Guice 创建的(通过 Injector.getInstance(...) 或通过传递注入到由Guice),那么注入字段不可能为 null,也不可能使用 null 调用注入方法,除非参数已显式声明 @Nullable 。如果 Guice 必须注入一个无法解析依赖关系的对象,那么它将抛出异常。

当然,这是 Guice 如何注入(或不注入)内容的简化解释。重要的是第 3 点,这让我相信注入字段为 null 的实例不是由 Guice 创建的,而是直接用 new 实例化的。

Although the question is not very clear, I'll try to clarify some situations where injection would occur or not occur, so you can see what problem you may face:

  1. If class A has @Inject fields, constructor or methods, but is directly instantiated by new somewhere in the code, then it won't normally get injected.

  2. Actually in the situation above, injection may occur if the instance was explicitly "marked" for injection in a Module, by calling injectMembers().

  3. If a class A has @Inject fields, constructor or methods, and it is created by Guice (either by Injector.getInstance(...) or by being transitively injected in an instance created by Guice), then it is not possible that injected fields be null or injected methods be called with null except if parameters have been explicitly declared @Nullable. If Guice must inject an object which dependencies can't be resolved then it will throw an exception.

Of course, this is a simplified explanation of how Guice injects (or not) stuff. What is important is point 3. which makes me believe that the instances for injected fields are null have not been created by Guice but directly instantiated with new.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文