如何在 HK2 中定义 "default" 实现?

How do I define a "default" implementation in HK2?

我正在使用 HK2 来解决我的 Jersey / Jetty Web 服务中的服务依赖关系。我有一种情况,对于一个特定的接口,我想使用一个特定的实现作为 "default" 实现。 "default" 我的意思是没有名称或限定符 - 如果您没有在字段或参数上指定任何注释,这就是您得到的结果。但是,在一些非常具体的情况下,我想提供一个替代实现,该实现将使用注释进行限定。

作为我实验的结果,我实际上通过在我的绑定中使用 ranked() 限定符使它可靠地工作。似乎最高等级成为默认等级。但是,我不明白它为什么会起作用,而且我担心我正在编写的代码依赖于 HK2 的一个未记录的实现细节,当我们更新版本时这些细节可能会改变。

这是我正在做的有趣部分的人为示例。 我应该使用 ranked() 来指定 "default" 和带注释的服务变体吗?我应该使用其他技术吗?

public interface IFoo {
    public String getString();
}

public class DefaultImpl implements IFoo {
    public String getString() {
        return "Default Implementation";
    }
}

public class AnnotatedImpl implements IFoo {
    public String getString() {
        return "Annotated Implementation";
    }
}

public class Bindings extends AbstractBinder {

     @Override
     public void configure() {
         ServiceBindingBuilder<DefaultImpl> defaultImpl =
             bind(DefaultImpl.class)
                 .to(IFoo.class);

         defaultImpl.ranked(9);

         ServiceBindingBuilder<AnnotatedImpl> annotatedImpl =
             bind(AnnotatedImpl.class)
                 .qualifiedBy(new MyAnnotationQualifier())
                 .to(IFoo.class);

         annotatedImpl.ranked(1);
     }
}

public class MyService {

    @Inject
    public MyService(
        IFoo defaultImplementation,
        @MyAnnotation
        IFoo annotatedImplementation) {

        // ... my code here ... 
    }
}

我在 HK2 的网站上偶然发现了一些与我所看到的行为一致的文档。

If there are more than one Widget (e.g. Widget is an interface that can have many implementations) then the best Widget will be returned from the getService method.

Services are sorted by (in order) the service ranking, the largest locator id (so that services in children are picked before services in parents) and smallest service id (so that older services are picked prior to newer services). Therefore the best instance of a service is a service with the highest ranking or largest service locator id or the lowest service id. The ranking of a service is found in its Descriptor and can be changed at any time at run time. The locator id of a service is a system assigned value for the Descriptor when it is bound into the ServiceLocator and is the id of that ServiceLocator. The service id of a service is a system assigned value for the Descriptor when it is bound into the ServiceLocator. The system assigned value is a monotonically increasing value. Thus if two services have the same ranking the best service will be associated with the oldest Descriptor bound into the system.

Source

因此,我在我的绑定上正确使用了 ranked()。它是控制 HK2 定义为“默认”(或“最佳”)服务以注入我的依赖服务的两种方式之一。