Java Guice - 如何将整数值绑定到我的类/对象?

时间:2013-12-22 16:27:59

标签: java dependency-injection guice

我不明白在绑定类时如何简单地绑定任何值。我总是得到这个错误:

No implementation for test.Triangle annotated with @com.google.inject.name.Named(value=triangle) was bound.

我试过了:

三角课

@Inject
public void setLength(@Named("triangle") int length) {
    this.length = length;
}

配置类

bind(Triangle.class).annotatedWith(Names.named("triangle")).toInstance(1); //this one just gives error that I can't do that.

如何在其中输入值,因此它将使用setLength方法和我选择的值?..我阅读了Guice文档,但没有找到它。在Spring框架中,像这样的东西似乎更容易做和理解(也许它有更好的文档,至少对我而言)。此外,如果我在文档中错过了显示此类事物,您也可以链接它。

1 个答案:

答案 0 :(得分:3)

bind(Integer.class).annotatedWith(Names.named("triangle")).toInstance(1);

您不希望将Triangle绑定到1 - 您希望将Integer绑定到1.最好使用@Named("triangleLength")或甚至切换到绑定注释({ {1}})明确意图。