Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guice: Avoid lazy injection

Tags:

guice

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?

like image 937
javaNoober Avatar asked Feb 13 '12 03:02

javaNoober


People also ask

What does @inject do in Guice?

Note that the only Guice-specific code in the above is the @Inject annotation. This annotation marks an injection point. Guice will attempt to reconcile the dependencies implied by the annotated constructor, method, or field.

What is eager singleton in Guice?

Guice provides special syntax for making an object that has the singleton scope, and is initialized to eager mode rather than lazy mode. Following is the syntax: bind(NotificationService. class).to(SMSService.

What is @inject annotation in Guice?

Annotation Type Inject. @Target(value={METHOD,CONSTRUCTOR,FIELD}) @Retention(value=RUNTIME) @Documented public @interface Inject. Annotates members of your implementation class (constructors, methods and fields) into which the Injector should inject values.

What is @named annotation in Guice?

4.1. We can use the optional @Named annotation as a qualifier to implement targeted injection based on the name.


1 Answers

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());
like image 128
Mark Peters Avatar answered Oct 16 '22 17:10

Mark Peters