¿Cuál es la diferencia entre estas dos declaraciones vinculantes con Google Guice?

Cuál es la diferencia entre

bind(FooImpl.class).in(Scopes.SINGLETON);
bind(Foo.class).to(FooImpl.class);

and

bind(Foo.class).to(FooImpl.class).in(Scopes.SINGLETON);

With Google Guice?

editar:

The second declaration create two instances on Singleton in a project I am working on. Referencia aquí

preguntado el 12 de junio de 12 a las 19:06

2 Respuestas

In referencia to Google Guice documentation:

In linked bindings, scopes apply to the binding source, not the binding target. Suppose we have a class Applebees that implements both Bar and Grill interfaces. These bindings allow for two instances of that type, one for Bars and another for Grills:

bind(Bar.class).to(Applebees.class).in(Singleton.class);
bind(Grill.class).to(Applebees.class).in(Singleton.class);

This is because the scopes apply to the bound type (Bar, Grill), not the type that satisfies that binding (Applebees). To allow only a single instance to be created, use a @Singleton annotation on the declaration for that class. Or add another binding:

bind(Applebees.class).in(Singleton.class);

So, It's possible to have two instances of FooImpl in the second way but not with the first way of writing the binding.

Respondido el 12 de junio de 12 a las 20:06

There is no difference. Both will bind Foo a una instancia de FooImpl en la SINGLETON alcance.

Respondido el 12 de junio de 12 a las 19:06

There is a difference, in a project I am working on, we just discover that the second instance caused 2 instances of the singleton. - Pier-Alexandre Bouchard

Oh, my mistake, you appear to have the correct answer. BTW, if you had mentioned what the difference in the result of the two approaches was, it may have helped figure out whether/how they were different. - Jason Hall

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.