java 如何让 Guice 模块使用另一个 Guice 模块?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7128327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to have a Guice module use another Guice module?
提问by Noel Yap
Let's say I have a Guice module ProdModule that I would like to depend on other GuiceModules, ProdDbModule and ProdPubSubModule. How would I implement ProdModule's configure()?
假设我有一个 Guice 模块 ProdModule,我想依赖其他 GuiceModules、ProdDbModule 和 ProdPubSubModule。我将如何实现 ProdModule 的 configure()?
回答by Jeremy
回答by ColinD
While it can be convenient to use install
, you don't even need to install
the other modules as long as you provide all the necessary modules when you create your Injector
:
虽然使用起来很方便install
,但你甚至不需要install
其他模块,只要你在创建你的时候提供所有必要的模块Injector
:
Injector injector = Guice.createInjector(new ProdDbModule(),
new ProdPubSubModule(), new ProdModule());
This can give you more flexibility to change out just one of these modules in your entry point class without needing to modify ProdModule
itself. You can also indicate in a module what bindings it requires other modules to provide using the requireBinding
methods.
这可以让您更灵活地更改入口点类中的这些模块之一,而无需修改ProdModule
自身。您还可以在模块中指明它需要其他模块使用这些requireBinding
方法提供哪些绑定。
回答by Alex
You can use Modules.combine
to create a new module that contains all the other modules. (See this link)
您可以使用Modules.combine
来创建一个包含所有其他模块的新模块。(见此链接)
The differences:
区别:
- this is not subject to tight coupling modules like
install()
- this creates a
Module
rather than an injector, which means you can easily add different modules to the injector.
- 这不受紧耦合模块的影响,例如
install()
- 这将创建一个
Module
而不是注入器,这意味着您可以轻松地向注入器添加不同的模块。
Code
代码
import com.google.inject.util.Modules;
Module module = Modules.combine(new ProdDbModule(),
new ProdPubSubModule(), new ProdModule());
Injector injector = Guice.createInjector(module);