I'm working on some Java Jersey stuff and would like to do the following;
I've got a class called SerialSubject:
public class SerialSubject{
private final SomeDatabase someDatabase;
@Inject
public SerialSubject(SomeDatabase someDatabase){
this.someDatabase = someDatabase;
initializeSerial();
}
InitializeSerial(){
SerialConfig config = SomeDatabase.getConfig();
//Open a Serial connection using this config
}
}
I'm binding this class using an AbstractBinder and register it to my ResourceConfig as per usual.
bind(SerialSubject.class).to(SerialSubject.class).in(Singleton.class)
All good and well, the dependency is resolved when requested by a resource and the serial connection is opened.
Now the caveat: I want to open the Serial connection at startup time. Is there any way to instantiate the class immediately? Constructing it manually won't do, as the database(which is already bound to ioc) is needed to retrieve the configuration.
You could use the Immediate
scope
Immediate is a scope that operates like
javax.inject.Singleton
scope, except that instances are created as soon as their correspondingDescriptor
s are added. When the correspondingDescriptor
is removed from the locator theImmediate
scope service is destroyed. In particularImmediate
scope services are not destroyed if theServiceHandle.destroy()
method is called. Care should be taken with the services injected into an immediate service, as they also become virtual immediate services
bind(SerialSubject.class).to(SerialSubject.class).in(Immediate.class)
You will also need to configure the ServiceLocator
to enable the immediate scope.
public class JerseyApplication extends ResourceConfig {
@Inject
public JerseyApplication(ServiceLocator locator) {
ServiceLocatorUtilities.enableImmediateScope(locator);
}
}
See also: