【问题标题】:Getting hk2 and Jersey to inject classes让 hk2 和 Jersey 注入课程
【发布时间】:2018-03-16 19:12:59
【问题描述】:

如何让 Jersey 注入类,而无需一对一地创建和注册工厂?

我有以下配置:

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 现在将成功注入 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
}

但这不是我的目标。我的目标是注入包装这些类的对象。有很多,它们每个都消耗 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 的实际工作原理,无法得出答案,而且这似乎是一个足够常见的问题,应该有一个简单的解决方案。

【问题讨论】:

    标签: java dependency-injection jersey hk2


    【解决方案1】:

    工厂实际上只需要更复杂的初始化。如果你不需要这个,你需要做的就是绑定服务

    @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 知道注入FooBaz

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

    【讨论】:

    • 已编辑以添加有关如何以更自动化的方式添加类的注释。如果有更具体的 hk2 方法,我会很高兴听到它。
    • 编辑被拒绝,所以我创建了一个新答案来包含最终解决方案。
    【解决方案2】:

    我最终使用FastClasspathScanner 从我感兴趣的包中获取类。然后我批量调用适当的绑定方法(bindAsContractbind),如Paul Samsotha's answer 中所述(在添加适当的@Inject 注释之后)。

    这似乎是模拟自动扫描并避免手动注册每个类的最方便的方法。

    感觉就像是 hack,如果 hk2 没有更好的方法,我会感到惊讶。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-13
      • 2014-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-03
      • 1970-01-01
      相关资源
      最近更新 更多