如何干净地覆盖Jersey使用的默认ServiceLocator?

ins*_*itu 4 java rest jersey jersey-2.0

我正在开发一个应用程序,它使用Jersey(2.5)作为其REST前端,Jetty作为嵌入式HTTP(S)服务器,两者都采用所谓的"嵌入式"方式,例如.不.war 依靠制作和部署它,而是通过处理程序,资源,注入的程序化配置......

我想以某种方式覆盖ServiceLocatorJersey在服务器端使用的HK2 ,或者可能为父服务定位器提供一个父服务器来解析在应用程序的REST部分之外定义的依赖关系.从我看到的代码来看,这似乎是不可能的:ServiceLocator在ApplicationHandler通过调用内部实例化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);
    }
Run Code Online (Sandbox Code Playgroud)

注射中的代码告诉我以下内容:

 public static ServiceLocator createLocator(Binder... binders) {
    return _createLocator(null, null, binders);
 }
Run Code Online (Sandbox Code Playgroud)

这意味着新创建的服务定位器具有一些任意生成的名称,并且没有父项.

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

小智 5

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

final ServiceLocator locator = (ServiceLocator) webConfig.getServletContext()
            .getAttribute(ServletProperties.SERVICE_LOCATOR);
Run Code Online (Sandbox Code Playgroud)

这段代码在jerseyes WebComponent构造器中.所以解决方案是提供ServletProperties.SERVICE_LOCATOR给你的ServletContext.在Dropwizard环境中,我实现了它

environment.getApplicationContext().getAttributes().setAttribute(ServletProperties.SERVICE_LOCATOR, locator);
Run Code Online (Sandbox Code Playgroud)