gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:54:49 24 4
gpt4 key购买 nike

我正在使用 HK2 解决我的 Jersey/Jetty 网络服务中的服务依赖关系。我有一种情况,对于一个特定的接口(interface),我想使用一个特定的实现作为“默认”实现。 “默认”是指没有名称或限定符——如果您没有在字段或参数上指定任何注释,它就是您得到的。但是,在一些非常具体的情况下,我想提供一个将使用注释限定的替代实现。

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

这是我正在做的有趣部分的人为示例。 我应该使用 ranked() 来指定服务的“默认”和注释变体吗?我应该使用另一种技术吗?

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

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

关于java - 如何在 HK2 中定义 "default"实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35994965/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com