I am developing an application that uses Jersey (2.5) as its REST front-end, and Jetty as embedded HTTP(S) server, both in a so-called "embedded" way, eg. without resorting to making .war
and deploying it but through programmatic configuration of handlers, resources, injections...
I would like to somehow override the HK2 ServiceLocator
that is used on the server side by Jersey, or possibly provide this service locator with a parent for resolving dependencies that are defined outside of the REST part of the application. From what I see of the code, this does not seem possible: The ServiceLocator is instantiated inside the ApplicationHandler
through a call to Injections
:
if (customBinder == null) {
this.locator = Injections.createLocator(new ServerBinder(application.getProperties()), new ApplicationBinder());
} else {
this.locator = Injections.createLocator(new ServerBinder(application.getProperties()), new ApplicationBinder(),
customBinder);
}
And the code in Injections tells me the following:
public static ServiceLocator createLocator(Binder... binders) {
return _createLocator(null, null, binders);
}
which means the newly created service locator has some arbitrarily generated name and has no parent.
Is there a (clean) way to change this behaviour so that I inject my own ServiceLocator as a parent of the application's?
I know that this answer is a little late. I struggled with the same issue, but in the Dropwizard framework. After some debugging, I saw the some lines of code which made me happy!
final ServiceLocator locator = (ServiceLocator) webConfig.getServletContext()
.getAttribute(ServletProperties.SERVICE_LOCATOR);
This piece of code is inside of the jerseyes WebComponent constuctor. So the solution is to provide ServletProperties.SERVICE_LOCATOR
to your ServletContext. In the Dropwizard environment, I achieved it by doing
environment.getApplicationContext().getAttributes().setAttribute(ServletProperties.SERVICE_LOCATOR, locator);
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