如何干净地覆盖Jersey使用的默认ServiceLocator? [英] How can I cleanly override the default ServiceLocator used by Jersey?

查看:117
本文介绍了如何干净地覆盖Jersey使用的默认ServiceLocator?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,它使用Jersey(2.5)作为其REST前端,Jetty作为嵌入式HTTP(S)服务器,两者都采用所谓的嵌入式方式,例如。没有诉诸 .war 并部署它,但通过处理程序,资源,注入的程序化配置......

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

我想以某种方式覆盖由Jersey在服务器端使用的HK2 ServiceLocator ,或者可能提供此服务定位器以及用于解析在外部定义的依赖关系的父服务定位器。 REST部分应用程序。从我看到的代码来看,这似乎是不可能的:ServiceLocator通过调用 Injections ApplicationHandler 中实例化。 c>:

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.

是否有(干净的)方法来改变这种行为,以便我将自己的ServiceLocator作为应用程序的父级注入?

Is there a (clean) way to change this behaviour so that I inject my own ServiceLocator as a parent of the application's?

推荐答案

我知道这个答案有点晚了。我在同样的问题上挣扎,但在Dropwizard框架中。经过一些调试后,我看到一些令我高兴的代码行!

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);

这段代码位于jerseyes WebComponent构造函数内。因此,解决方案是向您的ServletContext提供 ServletProperties.SERVICE_LOCATOR 。在Dropwizard环境中,我通过执行它来实现它

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);

这篇关于如何干净地覆盖Jersey使用的默认ServiceLocator?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆