如何让 Jersey 注入(inject)类而不需要一对一地创建和注册工厂?
我有以下配置:
public class MyConfig extends ResourceConfig {
public MyConfig() {
register(new AbstractBinder() {
@Override
protected void configure() {
bindFactory(FooFactory.class).to(Foo.class);
bindFactory(BazFactory.class).to(Baz.class);
}
});
}
}
hk2 现在将成功注入(inject) Foo 和 Baz:
// this works; Foo is created by the registered FooFactory and injected
@GET
@Path("test")
@Produces("application/json")
public Response getTest(@Context Foo foo) {
// code
}
但这不是我的目标。我的目标是注入(inject)包装这些类的对象。有很多,它们各自消耗 Foo 和 Baz 的不同组合。一些例子:
public class FooExtender implements WrapperInterface {
public FooExtender(Foo foo) {
// code
}
}
public class FooBazExtender implements WrapperInterface {
public FooBazExtender(Foo foo, Baz baz) {
// code
}
}
public class TestExtender implements WrapperInterface {
public TestExtender(Foo foo) {
// code
}
// code
}
等等。
以下方法不起作用:
// this does not work
@GET
@Path("test")
@Produces("application/json")
public Response getTest(@Context TestExtender test) {
// code
}
我可以为每个工厂创建一个工厂,并将其注册到我的应用程序配置类中,使用 bindFactory
语法,就像我对 Foo 和 Baz 所做的那样。但由于所涉及的对象数量较多,这不是一个好方法。
我阅读了很多 hk2 文档,并尝试了多种方法。我只是不太了解 hk2 的实际工作原理,无法给出答案,而且这似乎是一个很常见的问题,应该有一个简单的解决方案。
最佳答案
工厂实际上只需要更复杂的初始化。如果不需要这个,只需绑定(bind)服务即可
@Override
protected void configure() {
// bind service and advertise it as itself in a per lookup scope
bindAsContract(TestExtender.class);
// or bind service as a singleton
bindAsContract(TestExtender.class).in(Singleton.class);
// or bind the service and advertise as an interface
bind(TestExtender.class).to(ITestExtender.class);
// or bind the service and advertise as interface in a scope
bind(TestExtender.class).to(ITestExtender.class).in(RequestScoped.class);
}
您还需要在构造函数上添加@Inject
,以便 HK2 知道注入(inject) Foo
和 Baz
@Inject
public TestExtender(Foo foo, Baz baz) {}
关于java - 让 hk2 和 Jersey 注入(inject)类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49327986/