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?
Yes, bind it using
.asEagerSingleton():Note that according to that link,
Guicewill eagerly create allSingletons if being run in thePRODUCTIONstage (it lazily creates them in theDEVELOPMENTstage for faster test deployment). You can specify theStagewhen creating theInjector: