gpt4 book ai didi

java - 注入(inject)具有通用类型@Inject Guice 的类时出错

转载 作者:行者123 更新时间:2023-11-30 07:56:59 25 4
gpt4 key购买 nike

我正在尝试使用带有 @Inject 注释的 Guice 在另一个类(比如 ClassB)中注入(inject)一个通用类型的类(比如 ClassA)。被注入(inject)类的代码如下所示:

public interface InterfaceA<T> {

}

public class ClassA<T> implements InterfaceA<T> {
private final Class<T> data;
private Dependency1 dependency1;

@Inject
public ClassA(Class<T> data, Dependency1 dependency1) {
this.data = data;
this.dependency1 = dependency1;
}

}

ClassB的代码如下:

public class ClassB {
private InterfaceA<Entity1> interfaceA;

@Inject
public ClassB(InterfaceA<Entity1> interfaceA) {
this.interfaceA = interfaceA;
}
}

模块类如下:

public class MyModule extends AbstractModule {
@Override
protected void configure() {
bind(new TypeLiteral<InterfaceA<Entity1>>(){}).to(new TypeLiteral<InterfaceA<Entity1>>(){});
}
}

但是,当应用程序启动时,出现以下错误:

ERROR [2017-01-14 19:54:00,646] com.hubspot.dropwizard.guice.GuiceBundle: Exception occurred when creating Guice Injector - exiting
! com.google.inject.CreationException: Unable to create injector, see the following errors:
!
! 1) Could not find a suitable constructor in java.lang.Class. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private.
! at java.lang.Class.class(Class.java:119)

任何有关如何解决此问题的意见都会非常有帮助。提前致谢。

最佳答案

您不能以声明的方式执行此操作。您必须使用提供者方法:

public class MyModule extends AbstractModule {
@Override protected void configure() {}

@Provides InterfaceA<Entity1> provideInterfaceAEntity1(Dependency1 dep) {
return new ClassA<Entity1>(Entity1.class, dep);
}
}

这是唯一的方法,因为你不能自动注入(inject) Class<T>ClassA .

您的 Module 中需要这样的方法对于每个 Entity你想搭配 InterfaceA .

关于java - 注入(inject)具有通用类型@Inject Guice 的类时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41651164/

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