How to determine the default implementation in HK2?

I use HK2 to resolve service dependencies in the Jersey / Jetty web service. I have a situation where for one specific interface I want to use a specific implementation as the default implementation. By default, I mean the absence of names or classifiers - this is what you get if you do not specify any annotations on top of the field or argument. However, in a few very specific situations, I want to provide an alternative implementation that will qualify using annotation.

As a result of my experiments, I really got this to work reliably using the ranked() qualifier in my bindings. Apparently, the highest rank becomes default. However, I donโ€™t understand why this works, and I am worried that I am writing code that depends on the undocumented details of the HK2 implementation, which may change when upgrading versions.

Here is a contrived example of interesting parts of what I am doing. Is ranked() what I should use to indicate the "default" and annotated service options? Should I use a different technique?

 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 ... } } 
+1
source share
1 answer

I stumbled upon some documentation on the HK2 website that matches the behavior I see.

If there is more than one widget (for example, Widget is an interface that can have many implementations), the best Widget method will be returned from the getService method. The best instance of a service is the one with the highest rating or lowest service identifier. The ranking of a service is in its descriptor and can be changed at any time at runtime. The service service identifier is the system assigned value for the handle when it is associated with the ServiceLocator. The system assigned value is a monotonically increasing value. Thus, if two services have the same rating, the best service will be associated with the oldest descriptor associated with the system.

A source

Therefore, I am using ranked() correctly for my bindings. This is one of two ways to control what HK2 defines as the โ€œdefaultโ€ (or โ€œbestโ€) service to enter into my dependent services.

+2
source

Source: https://habr.com/ru/post/1242256/


All Articles