相关疑难解决方法(0)

使用Jersey 2.0进行依赖注入

从头开始没有任何以前的Jersey 1.x知识,我很难理解如何在我的Jersey 2.0项目中设置依赖注入.

我也明白HK2可用于Jersey 2.0,但我似乎无法找到有助于Jersey 2.0集成的文档.

@ManagedBean
@Path("myresource")
public class MyResource {

    @Inject
    MyService myService;

    /**
     * Method handling HTTP GET requests. The returned object will be sent
     * to the client as "text/plain" media type.
     *
     * @return String that will be returned as a text/plain response.
     */
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/getit")
    public String getIt() {
        return "Got it {" + myService + "}";
    }
}

@Resource
@ManagedBean
public class MyService {
    void serviceCall() {
        System.out.print("Service calls");
    }
}
Run Code Online (Sandbox Code Playgroud)

的pom.xml …

java dependency-injection jersey jersey-2.0 hk2

106
推荐指数
4
解决办法
9万
查看次数

如何在 HK2 中定义“默认”实现?

我正在使用 HK2 来解决我的 Jersey / Jetty Web 服务中服务的依赖关系。我有一种情况,对于一个特定的接口,我想使用特定的实现作为“默认”实现。“默认”我的意思是没有名称或限定符 - 如果您没有在字段或参数顶部指定任何注释,这就是您得到的。但是,在一些非常特殊的情况下,我想提供一个可以使用注释限定的替代实现。

作为我的实验的结果,我实际上通过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()) …
Run Code Online (Sandbox Code Playgroud)

java dependency-injection jersey dependency-management hk2

2
推荐指数
1
解决办法
846
查看次数