14

I have a class Cache which is quite expensive to create, but after that is set as a singleton and injected into my service layer.

@Override
protected void configure() {            
    bind(Cache.class).in(Singleton.class);

    bind(Service.class).to(ServiceImpl.class).in(Singleton.class);      
}

@Inject
    public ServiceImpl(Cache cache){
        this.cache = cache;
    }

public Cache(){
//Expensive stuff
}

My problem is it seems public() in Cache only executes when I'm trying to access one of its methods

Can I somehow make the object get constructed on server startup instead?

javaNoober
  • 1,338
  • 2
  • 17
  • 43

1 Answers1

26

Yes, bind it using .asEagerSingleton():

bind(Service.class).to(ServiceImpl.class).asEagerSingleton(); 

Note that according to that link, Guice will eagerly create all Singletons if being run in the PRODUCTION stage (it lazily creates them in the DEVELOPMENT stage for faster test deployment). You can specify the Stage when creating the Injector:

Injector injector = Guice.createInjector(Stage.PRODUCTION, new MyModule());
Ben McCann
  • 18,548
  • 25
  • 83
  • 101
Mark Peters
  • 80,126
  • 17
  • 159
  • 190