Mlezi Mlezi - 1 month ago 10
Java Question

Java Jersey construct class at bind time

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;

public SerialSubject(SomeDatabase someDatabase){
this.someDatabase = someDatabase;

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.


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 corresponding Descriptors are added. When the corresponding Descriptor is removed from the locator the Immediate scope service is destroyed. In particular Immediate scope services are not destroyed if the ServiceHandle.destroy() method is called. Care should be taken with the services injected into an immediate service, as they also become virtual immediate services


You will also need to configure the ServiceLocator to enable the immediate scope.

public class JerseyApplication extends ResourceConfig {

    public JerseyApplication(ServiceLocator locator) {

See also: