Mlezi Mlezi - 12 days ago 6
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;

@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.

Answer

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

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: