java - 将服务类与泛型绑定(bind)

标签 java jersey jersey-2.0 hk2

我有一个通用接口(interface)

@FunctionalInterface
public interface GenericInterface<T> {

    Optional<T> doSmth(long Id);
}

我有两个实现类,例如 GenericInterfaceImpl 和 GenericInterfaceImplImpl,它们都在一个方法中使用自己的类作为泛型

public class GenericInterfaceImpl
    implements GenericInterface<OwnClass> {
}

public class GenericInterfaceImplImpl
    implements GenericInterface<OwnClass2> {
}

我还有另外两个类,它们应该使用上述服务的依赖项

public class Class1 {
private final GenericInterface<OwnClass> gen;
@Inject
public Class1(GenericInterface<OwnClass> gen) {
this.gen = gen;
}
}

public class Class2 {
private final GenericInterface<OwnClass2> gen2;
@Inject
public Class2(GenericInterface<OwnClass2> gen2) {
this.gen2 = gen2;
}
}

ServiceBinder class

bind(GenericInterfaceImpl.class).to(GenericInterface.class);
bind(GenericInterfaceImplImpl.class).to(GenericInterface.class);

运行应用程序后,假设我已经注册了ServiceBinder,我收到此错误

Caused by: org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=GenericInterface,parent=Class1 etc.)

如何正确绑定(bind)?

最佳答案

经过8个小时的搜索,我找到了解决方案

   bind(GenericInterfaceImpl.class).to(new TypeLiteral<GenericInterface<OwnClass>>() {});
   bind(GenericInterfaceImplImpl.class).to(new TypeLiteral<GenericInterface<OwnClass2>>(){});

关于java - 将服务类与泛型绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61504272/

相关文章:

java - Apache Jersey 异常 :java. lang.NoSuchMethodError : org. glassfish.hk2.utilities.AbstractActiveDescriptor

java - 如何使用 Android 将文档上传到 SharePoint?

java - 如何将隐藏值从 Thymeleaf 模板传递到 Controller (Spring Boot)?

jpa - Jersey + HK2 + 灰熊 : Proper way to inject EntityManager?

java - 我应该如何将我的用户名和密码发送到 Java 后端?

java - 无法使用 Spring Boot 和 Jersey 2 提供静态内容

java - IntelliJ 无法使用 OpenJDK 11 识别 JavaFX 11

Java 元信息服务

java - 使用 Jersey 客户端的连接池

java - 泽西响应过滤器