使用Guice注入具有不同参数的相同组件 [英] Inject the same component with different parameters with Guice
问题描述
我有一个Class,它代表图形组件.该组件显示数据库中的数据.
I have a Class which represents a graphical Component. This component displays data from the database.
现在我有某种仪表板,上面有我的12个组件.我当然想重用这个组件!所以我想,我可以使用带有参数的自定义注释,然后将参数传递给提供程序.我在Stackoverflow上发现了一些骇客内容(http://stackoverflow.com/questions/5704918/custom-guice-binding-annot ...),但老实说,我没有找到任何文档来了解如何为自定义接口实现AnnotationImpl
Now I have some kind of dashboard, which has 12 of my Components above. Of course I want to reuse this component! So I thought, I could use a Custom Annotation with parameters and pass the parameters to a provider. I found some hack on Stackoverflow (http://stackoverflow.com/questions/5704918/custom-guice-binding-annot...) but to be honest, I did not find any documentation how to implement an AnnotationImpl for my Custom Interface.
我不认为AssistedInject是我在这里需要的,因为我不喜欢通过AssistedInjection向我的构造函数注入12x相同类的想法.
I do not think, that AssistedInject is what I need here, because I do not like the idea to inject 12x the same Class via AssistedInjection to my constructor.
对我来说,不行的是只针对一个不同的参数编写一个Interface和12个实现类.
A No-Go for me is to write an Interface and 12 implementation classes, just for one different parameter.
有人对我的问题有主意吗?
Has anyone an idea for my issue?
推荐答案
我不确定您要做什么,但我认为辅助注射可能适合您.您是否可以不创建ComponentFactory,然后在其create方法中指定所需的此参数?您甚至不需要创建Factory的具体实现,因为Guice会为您做到这一点,您可以像这样指定它:
I'm not exactly clear on what you're trying to do, but i think Assisted inject might be right for you. Can you not create a ComponentFactory and then, in it's create method, specify this parameter you need? You don't even need to create a concrete implementation of the Factory as Guice will do that for you and you can specify it like this:
install(new FactoryModuleBuilder().build(ComponentFactory.class));
ComponentFactory看起来像这样:
ComponentFactory would look like this:
public interface ComponentFactory {
Component create(ParameterType parameter);
}
组件本身是这样的:
public class Component {
@Inject
public WebClient(@Assisted ParameterType parameter, OtherService service) {
// etc...
}
}
然后,将ComponentFactory传递到仪表板,它可以(轻松地)创建所需的任何组件.
Then you pass the ComponentFactory to your Dashboard and it can create (easily) whatever Components it wants.
这篇关于使用Guice注入具有不同参数的相同组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!