xiaodududu / google-guice

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

@Singleton annotation on get() method of a Provider class shoudln't be silently ignored #736

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
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.

Original issue reported on code.google.com by pepst...@google.com on 3 Dec 2012 at 9:43