如何配置HK2注入通过工厂方法创建的对象? [英] How do I configure HK2 to inject an object created by a factory method?
问题描述
在HK2中,用于配置注入的基本示例代码如下(在扩展AbstractBinder
的类中:
In HK2 the basic example code for configuring injection is this (within a class that extends AbstractBinder
:
bind(BuilderHelper
.link(FooImpl.class) // the class of the object to be injected
.to(FooInterface.class) // identifies what @Inject fields to link to
.build());
这会导致HK2在需要创建FooInterface
时调用构造函数FooImpl()
.
This causes HK2 to call the constructor FooImpl()
when it needs to create a FooInterface
.
如果FooImpl没有构造函数怎么办?
What if FooImpl doesn't have a constructor?
- 如果要使用静态工厂方法实例化
FooImpl.getInstance()
,该怎么办
- 如果打算由工厂对象实例化
fooFactory.create()
,该怎么办
- What if it's intended to be instantiated with a static factory method
FooImpl.getInstance()
- What if it's intented to be instantiated by a factory object
fooFactory.create()
我看到ResourceConfig
具有方法bind(FactoryDescriptors factoryDescriptors)
,但是我不清楚用于构建FactoryDescriptors
对象的惯用法是什么,并且无法在线找到任何示例.
I see that ResourceConfig
has a method bind(FactoryDescriptors factoryDescriptors)
but it is not clear to me what the idiom is for building a FactoryDescriptors
object, and have not been able to find any examples online.
推荐答案
虽然我仍然看不到使用BuilderHelper EDSL进行操作的方法(对于一般情况,这似乎也太过苛刻了),但可以使用以下方法:
While I still can't see a way to do it using the BuilderHelper EDSL (it appears this is overkill for the common case too), the following works:
bindFactory(FooFactory.class)
.to(FooInterface.class);
这要求FooFactory
是Factory<FooInterface>
的实现,因此您需要围绕现有的任何工厂都有外观.我在需要它的时候作为私人内部类来做.
This requires that FooFactory
is an implementation of Factory<FooInterface>
, so you need a facade around any existing factory you have. I did it as a private inner class where I needed it.
private static class FooFactory implements Factory<FooInterface> {
@Override
public void dispose(FooInterface foo) {
// meh
}
@Override
public FooInterface provide() {
return SomeFactory.getInstance();
}
}
这篇关于如何配置HK2注入通过工厂方法创建的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!