Guice: Avoid Lazy Injections

I have a Cache class, which is quite expensive to create, but after that it is installed as a single element and introduced into my service level.

@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: it seems public () in the cache is only executed when trying to access one of its methods

Can I somehow create an object created when the server starts?

+5
source share
1 answer

Yes, bind it using .asEagerSingleton():

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

Please note that according to this link, he Guicewill look forward to creating everything Singletonif they are performed at the stage PRODUCTION(he lazily creates them at the stage DEVELOPMENTfor faster testing). You can specify Stagewhen creating Injector:

Injector injector = Guice.createInjector(Stage.PRODUCTION, new MyModule());
+10

All Articles