Jon Vaughan wrote:
> Hi,
>
> I'm new to Guice, so I apologise if this is a stupid question, or if
> my I'm just plain wrong. I'm trying to retrofit it to a large
> existing codebase.
>
> My understanding is that if I have a Guice binding like:
>
> bind(MyInterface.class).to(MyClass.class)
>
> where MyClass implements MyInterface and has a constructor like:
>
> @Inject
> public myClass(AnotherClass somethingElse)
> {
> //..blah
> }
>
> then when Guice supplies an instance of MyClass, that instance will
> have been injected with, in turn, an AnotherClass instance, providing
> that is also bound (hopefully I'm right so far?)
>
> So now imagine that MyClass does NOT implement MyInterface (classes in
> my codebase only implement interfaces where there are multiple
> implementations of that interface) .
>
> Guice does not permit me to do this:
>
> bind(MyClass.class).to.(MyClass.class)
You do not need it, this is a sort of default.
I'd say, wrinting only
bind(MyClass.class);
does what you wanted.
> And this is not the same thing:
>
> bind(MyClass.class).toInstance(new MyClass())
>
> because that instance will not have been supplied with an
> AnotherClass.
Right. Generelly, I try to avoid bind-toInstance.
In the case above annotating MyClass with @Singleton or using simply
bind(MyClass.class).asEagerSingleton()
or maybe
bind(MyClass.class).in(Scopes.SINGLETON);
may be better (I supose you want a singleton since you get one using
bind-toInstance).
> I could have some sort of bootstrap where I:
>
> bind(AnotherClass.class).toInstance(new AnotherClass());
>
> and then
>
> Injector injector = Guice.createInjector(getBootstrapModule());
> bind(MyClass.class).toInstance(injector.getInstance(MyClass.class));
>
> but then I'm stumped if I want to then inject both MyClass and
> AnotherClass into something, unless I can live with multiple instances
> of AnotherClass.
I think this could be solved using child injectors but this is currently too
high for me.
> I do not want to write interfaces for these classes just so I can
> inject them; have I got something wrong here, or is there a way around
> this?
You need no interfaces for this. Generally, you can use abstract or concrete
superclass instead of interface, and you need nothing if there's no hierarchy.
> Many thanks if you are able to help
Regards, Maaartin.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"google-guice" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/google-guice?hl=en
-~----------~----~----~----~------~----~------~--~---