Java Guice - 如何将整数值绑定到我的类/对象? [英] Java Guice - how to bind integer value to my class/object?

查看:81
本文介绍了Java Guice - 如何将整数值绑定到我的类/对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I don't understand how can I simply bind any value when I bind a class. I always get this error:

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); //这个只是给出了我无法做到的错误。

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

How can I enter a value into it, so it would use setLength method with my chosen value?.. I read Guice documentation, but didn't find it. In Spring framework such things like these seemed much easier to do and understand (maybe it has better documentation, at least for me). Also if I missed in documentation where it shows this kind of thing you can link it too.

推荐答案

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

您不想绑定 Triangle 到1 - 你想将 Integer 绑定到1.最好使用 @Named(triangleLength)甚至切换到绑定注释( @IndicatesTriangleLength )以明确意图。

You don't want to bind Triangle to 1 - you want to bind Integer to 1. It might be better to use @Named("triangleLength") or even switch to a binding annotation (@IndicatesTriangleLength) to make the intention clear.

这篇关于Java Guice - 如何将整数值绑定到我的类/对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆