本文介绍了如何定义“默认"广告代码?在HK2中实施?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用HK2来解决我的Jersey/Jetty Web服务中服务的依赖关系.我遇到一种情况,对于一个特定的接口,我想使用特定的实现作为默认"实现. 默认"是指没有名称或限定词-如果未在字段或参数的顶部指定任何注释,则会得到此名称.但是,在一些非常特殊的情况下,我想提供一种可选的实现,该实现将带有注释.

I am using HK2 to resolve dependencies of services in my Jersey / Jetty web service. I have a situation where for one particular interface, I want to use a specific implementation as a "default" implementation. By "default" I mean no names or qualifiers - it 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 be qualified with an annotation.

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

As a result of my experimentation I have actually got this to work reliably by using the ranked() qualifier in my bindings. It appears the highest rank becomes the default. However, I do not understand why it works, and I am concerned I am writing code that depends on an undocumented implementation detail of HK2 that could change when we update versions.

这是我正在做的有趣部分的一个精心设计的示例. ranked()是我应该用来指定服务的默认"和带注释的变体吗?我应该使用其他技术吗?

Here's a contrived example of the interesting parts of what I am doing. Is ranked() what I should be using to specify "default" and annotated variants of a service? Should I be using another 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 ...
    }
}

推荐答案

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

I stumbled across some documentation on HK2's website that is consistent with the behavior that I am seeing.

因此,我在绑定上正确使用了ranked().这是控制HK2定义为向我的从属服务注入的默认"(或最佳")服务的两种方法之一.

Therefore, I am using ranked() on my bindings correctly. It is one of the two ways to control what HK2 defines as the "default" (or "best") service to inject into my dependent services.

这篇关于如何定义“默认"广告代码?在HK2中实施?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 06:30