如何在需要注入实例的Guice中进行动态绑定? [英] How do you make dynamic bindings in Guice that require an injected Instance?
问题描述
我想创建一个将实例动态绑定到命名注释的模块。用例是我自动将配置中的值与属性文件中的键值绑定为@Named值。
I'd like to create a Module that dynamically binds instances to named annotations. The use case is I would like to automatically bind the values in my configuration with the key in the properties file being the @Named value.
但是配置绑定在不同的模块,所以我需要配置注入。我看过的解决方案是:
However the configuration is bound in a different module so I need the config to be injected. Solutions I've looked at are:
-
在configure()方法中绑定。
这个方法不会被注入,我无法获得基本配置。
Binding in the configure() method. This method is not injected into and I can not get the base configuration.
使用提供者/ @提供。
提供者只绑定单个实例。
Using a Provider/@Provides. Providers only bind a single instance.
使用MultiBinder。
我的用例与这个扩展名提供的有所不同。多绑定允许您单独绑定多个实例,然后将它们作为集合更为复杂的包含类型注入。我想分别绑定每个实例,并通过唯一的身份识别注入后者。
Using MultiBinder. My use case is a little different then what is provided by this extension. Multi-binding allows you to bind multiple instances separately and then have them injected as a Collection more complex containing type. I would like to bind each instance separately and have them by uniquely identifiable for injection latter.
使用childInjector。
不幸的是,如果没有对现有代码进行大量修改,这是不可能的。