I am porting some code from Jersey 1.x and my implementation of various Health Check endpoints relies on all the @Singleton
endpoint resources being initialized at start up so as to be able to detect which checks to do.
In Jersey 2.0 - whatever I do I can't seem to get my resource endpoints to initialise at start up and they are only constructed+initialized when each one is accessed for the first time.
I guess I could initialise them myself in the Application
class but I'd rather use the package scanning!
Does anyone have any idea if there is some config option that will tell Jersey 2 to eagerly initialise all resource endpoints that it finds during package scanning?
Or some HK2 annotation or trick?
"Or some HK2 annotation or trick?"
You can use HK2's Immediate Scope. Just annotate the resource class with @Immediate
(which acts like @Singleton
, so you can get rid of that), then enable the immediate scope on the ServiceLocator
. An example:
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.utilities.ServiceLocatorUtilities;
...
@ApplicationPath("/rest")
public class JerseyApplication extends ResourceConfig {
@Inject
public JerseyApplication(ServiceLocator locator) {
ServiceLocatorUtilities.enableImmediateScope(locator);
packages("thepackages.to.scan");
}
}
Based on this related question, if you need to explicitly instantiate the ResourceConfig
, as in the case of the linked question, you can create a Feature
and register the feature, as seen in this answer
Please see related issue
Looks like Immediate scope memory leak issue previously linked to has been resolved in version 2.22.1