google-code-export / google-guice

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

Stage.PRODUCTION doesn't load @Singletons eagerly #199

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
That is, given...

  void testAnnotatedSingletonEagerlyLoads() {
    Guice.createInjector(Stage.PRODUCTION, new AbstractModule() {
      protected void configure() {
        bind(Hoo.class).to(Har.class);
      }
    });
    assertEquals(1, Har.count);
  }

  static interface Hoo {}
  @Singleton
  static class Har implements Hoo {
    static int count = 0;
    public Har() {
      count++;
    }
  }

.... fails.  (Har.count == 0)

Original issue reported on code.google.com by sberlin on 15 May 2008 at 2:00

GoogleCodeExporter commented 9 years ago
The attached patch fixes the bug (and adds this test into PreloadingTest).  The 
premise is that eager-loaders are stored only if an explicit "asEagerSingleton" 
request is made on the command.  Those kinds of loaders are always run.  Then, 
if 
the stage is production, all bindings are iterated through and if the scope of 
the 
binding (or in the case of a linked binding with no explicit scope, the scope 
of its 
target binding) is singleton, the binding is also loaded.

It was a little more complicated than just changing LinkedBindingImpl because 
of all 
creationListeners had to be run before getScope() could be called, otherwise 
the 
target binding wouldn't have been created yet, which led into very weird JIT 
binding 
creations. 

Original comment by sberlin on 15 May 2008 at 2:57

Attachments:

GoogleCodeExporter commented 9 years ago
Fixed. I really liked your approach, so I took it one step further. 

Please code review rev 498 to see if it does what you want:
http://code.google.com/p/google-guice/source/detail?r=498

Original comment by limpbizkit on 2 Jun 2008 at 7:03

GoogleCodeExporter commented 9 years ago
A consequence of the fix is that Guice now eagerly loads all just-in-time 
@Singletons. We probably should have 
been doing this before.

Original comment by limpbizkit on 2 Jun 2008 at 4:45