Status: New
Owner: ----

New issue 736 by pepst...@google.com: @Singleton annotation on get() method of a Provider class shoudln't be silently ignored
http://code.google.com/p/google-guice/issues/detail?id=736

Putting the @Singleton annotation on a Provider class causes Guice to use the same instance of that provider every time it wants to create an instance. This can be useful, but what if you want the get method to be called just once? Of course you can specify this in the module with bind(Foo.class).to(FooProvider.class).in(Singleton.class);

I was thinking I could also specify this by annotating the get() method in my Provider class with @Singleton, but this doesn't work. The annotation is allowed on methods, but that seems to be for Provider methods. When applied to the get() method on a Provider class, it doesn't seem to have any effect. I think it should either make it a singleton or throw an exception to make it clear that it's not working.

Code to help make this clear:
public class Experiment {

  public static void main(String[] args) {
    Injector injector = Guice.createInjector(new MyModule());
    System.out.println(injector.getInstance(Integer.class));
    System.out.println(injector.getInstance(Integer.class));
  }

  private static class MyModule extends AbstractModule {
    @Override protected void configure() {
      bind(Integer.class).toProvider(IntegerProvider.class);
    }
  }

@Singleton private static class IntegerProvider implements Provider<Integer> {
    int i = 0;

    @Singleton @Override public Integer get() {
      return i++;
    }
  }
}

This code emits 0 and then 1, where I was hoping it'd emit two 0's.

--
You received this message because you are subscribed to the Google Groups 
"google-guice-dev" group.
To post to this group, send email to google-guice-dev@googlegroups.com.
To unsubscribe from this group, send email to 
google-guice-dev+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/google-guice-dev?hl=en.

Reply via email to