Java Guice - how to bind integer value to my class

2019-01-28 19:14发布

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.

I tried this:

Triangle class

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

Configuration class

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

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.

1条回答
Luminary・发光体
2楼-- · 2019-01-28 20:06
bind(Integer.class).annotatedWith(Names.named("triangle")).toInstance(1);

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.

查看更多
登录 后发表回答