Guice子注入器是否会自动创建?隐式创建场景咨询
Great question—this is one of those nuanced Guice behaviors that’s easy to overlook if you’re not digging into the right parts of the docs. Let’s break down your two questions clearly:
1. Will child injectors be automatically created for dependencies of dependencies?
Absolutely not. Guice injectors (parent or child) are explicitly created only when you call Injector.createChildInjector(). The entire dependency chain for any object is resolved by the injector you use to retrieve the top-level instance—either the parent injector, or a child injector you’ve explicitly instantiated.
For example:
- You create a parent injector with a binding for
ServiceA ServiceAdepends onServiceB, which depends onServiceC- All three classes will be instantiated and injected by the parent injector. There’s no scenario where Guice would spin up a child injector automatically to handle
ServiceBorServiceCunless you explicitly trigger it.
2. Will child injectors be automatically created for submodules?
Nope. Installing submodules via install(new MySubModule()) within a parent module merges the submodule’s bindings into the same injector instance—it does not create a child injector.
Submodules are just a way to organize and reuse binding configurations within a single injector. Child injectors, on the other hand, are separate, hierarchical instances that can override parent bindings while inheriting others. These are two completely distinct concepts in Guice.
Key Takeaway
Child injectors exist for intentional binding isolation (e.g., multi-tenant setups, environment-specific overrides, or temporary test bindings). Guice never creates them implicitly—every child injector in your codebase is the result of a deliberate call to createChildInjector().
内容的提问来源于stack exchange,提问作者Snow

