gpt4 book ai didi

java - 使用 Guice 注入(inject)泛型

转载 作者:IT老高 更新时间:2023-10-28 21:12:54 26 4
gpt4 key购买 nike

我正在尝试迁移一个小项目,用 Guice 替换一些工厂(这是我的第一次 Guice 试用版)。但是,我在尝试注入(inject)泛型时被卡住了。我设法提取了一个带有两个类和一个模块的小玩具示例:

import com.google.inject.Inject;

public class Console<T> {
private final StringOutput<T> out;
@Inject
public Console(StringOutput<T> out) {
this.out = out;
}
public void print(T t) {
System.out.println(out.converter(t));
}
}

public class StringOutput<T> {
public String converter(T t) {
return t.toString();
}
}

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.TypeLiteral;


public class MyModule extends AbstractModule {

@Override
protected void configure() {
bind(StringOutput.class);
bind(Console.class);
}

public static void main(String[] args) {
Injector injector = Guice.createInjector( new MyModule() );
StringOutput<Integer> out = injector.getInstance(StringOutput.class);
System.out.println( out.converter(12) );
Console<Double> cons = injector.getInstance(Console.class);
cons.print(123.0);
}

}

当我运行这个例子时,我得到的只是:

线程“main”com.google.inject.CreationException 中的异常:Guice 创建错误:

1) playground.StringOutput<T> cannot be used as a key; It is not fully specified.
at playground.MyModule.configure(MyModule.java:15)

1 error
at com.google.inject.internal.Errors.throwCreationExceptionIfErrorsExist(Errors.java:354)
at com.google.inject.InjectorBuilder.initializeStatically(InjectorBuilder.java:152)
at com.google.inject.InjectorBuilder.build(InjectorBuilder.java:105)
at com.google.inject.Guice.createInjector(Guice.java:92)

我尝试查找错误消息,但没有找到任何有用的提示。在 Guice FAQ 上,我偶然发现了一个关于如何注入(inject)泛型的问题。我尝试在 configure 方法中添加以下绑定(bind):

bind(new TypeLiteral<StringOutput<Double>>() {}).toInstance(new StringOutput<Double>());

但是没有成功(同样的错误信息)。

有人可以向我解释错误消息并提供一些提示吗?谢谢。

最佳答案

我认为您看到的具体问题可能是因为 bind(Console.class)陈述。它应该使用 TypeLiteral也是。或者,您可以不绑定(bind)其中任何一个,而 JIT 绑定(bind)将为您处理它,因为这里涉及的两种类型都是具体的类。

此外,您应该检索 Console与:

Console<Double> cons = 
injector.getInstance(Key.get(new TypeLiteral<Console<Double>>(){}));

编辑:您不需要仅仅因为您使用的是 TypeLiteral 就绑定(bind)到实例。 .你可以这样做:

bind(new TypeLiteral<Console<Double>>(){});

当然,就像我上面所说的,在这种情况下,您可以跳过它并检索 Console从注入(inject)器使用 Key基于TypeLiteral并且绑定(bind)是隐式的。

关于java - 使用 Guice 注入(inject)泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2581137/

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