java - 让 hk2 和 Jersey 注入(inject)类

标签 java dependency-injection jersey hk2

如何让 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) FooBaz

@Inject
public TestExtender(Foo foo, Baz baz) {}

关于java - 让 hk2 和 Jersey 注入(inject)类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49327986/

相关文章:

java - 即使步骤仍在运行,如何计算 ItemReader 中的 stepReads 以使中间结果可用?

java将对象保存在CPU寄存器中

android - 就良好架构而言,使用 DI(Dagger)的好例子是什么?

jakarta-ee - CDI:@Produces 方法在使用 AnnotationLiteral 调用实例后未注入(inject)

spring-mvc - Spring Rest中@Context UriInfo的等价物是什么

java - 比较和创建数组,而无需单独向数组添加元素

java - 无法在子类中使用 EventFiringWebDriver 对象

c# - 有人可以解释 Microsoft Unity 吗?

spring - HTTP 状态 415 - 执行 POST 时不支持的媒体类型

java - @RolesAllowed 不能在 Jersey 中使用自定义 SecurityContext?