pombreda / google-guice

Automatically exported from code.google.com/p/google-guice
Apache License 2.0
0 stars 1 forks source link

Guice is injecting members when binding an instance [bind().toInstance()]. #751

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
Hi,

I'm not sure if this is a bug but at least is worth to talk about it.

I noticed that when we perform a bind().toInstance() and the instance is an 
annotated class with @Inject etc, Guice will try to fill in those members.

My question is: is that suppose to happen? For me it was a surprise. Imagine 
the following use case:

You're running an application service where each service have their own 
dependency Guice instance and each of them publish some reference to a shared 
JNDI space.

The you need a reference to that service in another and you try to bind that 
service interface using bind().toInstance(). Guice will try to fill in the 
members that are already filled in. Well this is an issue, but not the only 
one. Imagine that each service run in it's classloader and inject members that 
are only visible in their context. It will fail saying that no implementation 
is bound (in fact that isn't) by the service trying to "re-inject" all the 
members again.

Well, again, I'm not saying it is a bug, but if it's not I think it's worth 
documenting about this behaviour.

I managed to to what I want using a provider that always returning the same 
instance. Is there any other way to do this?

Regards,

Rui

Original issue reported on code.google.com by rpvi...@gmail.com on 29 May 2013 at 7:03

GoogleCodeExporter commented 9 years ago
Yes it is expected: 
http://code.google.com/p/google-guice/wiki/Injections#Automatic_Injection

You can use the 
http://google-guice.googlecode.com/git/javadoc/com/google/inject/util/Providers.
html#of(T) utility method to skip this automatic injection. Alternatively add a 
@Provides method that returns the instance in your module: 
http://code.google.com/p/google-guice/wiki/ProvidesMethods

Original comment by mccu...@gmail.com on 29 May 2013 at 7:12

GoogleCodeExporter commented 9 years ago
I see, thanks!

--

Original comment by rpvi...@gmail.com on 29 May 2013 at 7:35

GoogleCodeExporter commented 9 years ago

Original comment by sberlin on 29 May 2013 at 7:42