如何将工厂绑定到注释合格的注入点?

Jin*_*won 2 testng unit-testing dependency-injection jersey hk2

了一个答案,如何绑定一个命名的注入点。

而且我不知道如何将工厂绑定到合格的注入点。

class SomeResource {

    @Inject
    @Some // is a @Qualifier, of course.
    private MyType qualified;
}
Run Code Online (Sandbox Code Playgroud)

我准备了一家工厂

class SomeFactory extends Factory<MyType> {
}
Run Code Online (Sandbox Code Playgroud)

我坚持为此创建活页夹

class SomeBinder extends AbstractBinder {
    @Override protected void configure() {
        // @@?
    }
}
Run Code Online (Sandbox Code Playgroud)

我实际上想知道如何使用ServiceBindingBuilder#qualifiedBy

Jin*_*won 5

我需要一个用于限定符注释的实现。

public class Some_
    extends AnnotationLiteral<Some>
    implements Some {
}
Run Code Online (Sandbox Code Playgroud)

这样我就可以这样使用。

bindFactory(Someactory.class)
    .qualifiedBy(new Some_())
    .to(MyType.class);
Run Code Online (Sandbox Code Playgroud)

我真的不明白为什么ServiceBindingBuilder没有采用注释类而不是实例的方法。

  • 另一个有趣的事情是,如果你有某种类型 X 的工厂并且它是绑定的,那么 Jersey 根本不会关心实际的注释。例如,您可以使用自定义一个或 Size(min=0)。它只需要字段/参数上的任何注释即可通过启动检查。稍后使用工厂注入该值。 (2认同)
  • 如果您自己找到了解决方案,您也可以接受自己的答案 (2认同)