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?
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.
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.
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.
4.1. We can use the optional @Named annotation as a qualifier to implement targeted injection based on the name.
Yes, bind it using .asEagerSingleton()
:
bind(Service.class).to(ServiceImpl.class).asEagerSingleton();
Note that according to that link, Guice
will eagerly create all Singleton
s 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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With