The slides contain the following bootstrapping code:
public class MyApplication {
public static void main(String[] args) {
Injector injector = Guice.createInjector();
Greeter greeter
= injector.getInstance(Greeter.class);
greeter.sayHello();
}
}
Now, there is a place in my application where I need to
conditionally create a new instance of a class. Someone invokes
getFoo() and if I can't find an existing instance in the database I
want to create one. Am I supposed to use Injector injector =
Guice.createInjector().getInstance(Foo.class)? Is there a way for me
to ask Guice for the existing Injector instance that was used to
generate the current object and then get back a Foo instance from it?
Thank you,
Gili
I suppose you could add @Inject Injector m_injector; to your class
(ie. the one with getFoo) - this should be populated with the injector
used to create that instance.
You could then call m_injector.getInstance(...etc...) inside getFoo.
The alternative approach would be to use some sort of thread-local
or session context to store the injector, where it could be retrieved
inside getFoo (however, this doesn't necessarily guarantee that it's
the same injector)
>
> Thank you,
> Gili
>
>
> >
>
--
Cheers, Stuart
Now, there is a place in my application where I need to
conditionally create a new instance of a class. Someone invokes
getFoo() and if I can't find an existing instance in the database I
want to create one. Am I supposed to use Injector injector =
Guice.createInjector().getInstance(Foo.class)? Is there a way for me
to ask Guice for the existing Injector instance that was used to
generate the current object and then get back a Foo instance from it?
http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/Injector.html
thanks for the good docs kevin and bob.
--
Gregory Kick
http://kickstyle.net/
thanks for the pointer - I hadn't seen the other bindings, such as logging...
> Contains several default bindings:
> * This Injector instance itself
> * A Provider<T> for each binding of type T
> * The Logger for the class being injected
> * The Stage in which the Injector was created
means I can throw out a lot more code from my demo application :)
>
> On 5/23/07, Bob Lee <craz...@crazybob.org> wrote:
> > On 5/23/07, Cow_woC <gili.t...@gmail.com> wrote:
> > > Now, there is a place in my application where I need to
> > > conditionally create a new instance of a class. Someone invokes
> > > getFoo() and if I can't find an existing instance in the database I
> > > want to create one. Am I supposed to use Injector injector =
> > > Guice.createInjector().getInstance(Foo.class)? Is there a way for me
> > > to ask Guice for the existing Injector instance that was used to
> > > generate the current object and then get back a Foo instance from it?
> >
> >
> > You can also @Inject Provider<Foo>.
> >
> > Bob
> >
> >
> > >
> >
>
>
> --
> Gregory Kick
> http://kickstyle.net/
>
> >
>
--
Cheers, Stuart