Comment by [email protected]:
I don't think it's clear from these examples that you don't have to do
anything different in your Module to use this functionality. It just works.
I think the article would be well served by a fully functional example that
you can just run and see it work.
{{{
import java.util.concurrent.atomic.AtomicInteger;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.Provider;
public class InjectProviderExample {
public static void main(String... args) {
Module myModule = new AbstractModule() {
@Override
protected void configure() {
// NOTICE THERE IS NO toProvider HERE
bind(Foo.class).to(FooImpl.class);
//
bind(Foo.class).to(FooImpl.class).in(Singleton.class);
}
};
Injector inj = Guice.createInjector(myModule);
Bar myBar = inj.getInstance(Bar.class);
Foo fooOne = myBar.getFoo();
Foo fooTwo = myBar.getFoo();
if(fooOne == fooTwo) {
System.out.println("This should not happen unless Singleton scope is
set");
} else {
System.out.format("FooOne id: %d\tFooTwo id: %d%n", fooOne.getId(),
fooTwo.getId());
}
}
public static interface Foo {
int getId();
}
public static class FooImpl implements Foo {
private static final AtomicInteger counter = new
AtomicInteger();
private int uid = counter.incrementAndGet();
public int getId() {
return uid;
}
}
public static class Bar {
private final Provider<Foo> myFooProvider;
@Inject
public Bar(Provider<Foo> fooProvider) {
myFooProvider = fooProvider;
}
public Foo getFoo() {
return myFooProvider.get();
}
}
}
}}}
For more information:
http://code.google.com/p/google-guice/wiki/InjectingProviders
--
You received this message because you are subscribed to the Google Groups
"google-guice-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/google-guice-dev.
For more options, visit https://groups.google.com/groups/opt_out.