简体   繁体   English

HK2依赖注入在多个servlet中

[英]HK2 dependency injection in multiple servlets

We have a REST API server based on Jetty 9.3 and Jersey 2.7 我们有一个基于Jetty 9.3和Jersey 2.7的REST API服务器

Dependency injection works fine with HK2 that comes bundled with the libs. 依赖注入对与libs捆绑在一起的HK2很好用。 We register the needed services to the application Handler via a ResourceConfig and have something like: 我们通过ResourceConfig向应用程序Handler程序注册所需的服务,并具有以下内容:

handler.addServlet(new ServletHolder("main-api", new ServletContainer(resourceConfig)), MAIN_SERVLET_PATH + "/*");

We then wanted to move some of the HTTP end-points to a separate "admin" port. 然后,我们想将一些HTTP端点移动到单独的“ admin”端口。 So we created two separate ServerConnector s, one for each port, and two separate Handler s wrapping separate ServletHolder s that are mapped to the relevant pathSpecs, for each relevant path ("/admin" and "/api"). 因此,我们为每个相关路径(“ / admin”和“ / api”)创建了两个单独的ServerConnector ,每个端口一个,以及两个单独的Handler ,它们包装了映射到相关pathSpecs的单独的ServletHolder

The problem is that each of the Handlers now creates a separate ServiceLocator with its own set of managed services. 问题在于,每个处理程序现在都使用其自己的托管服务集创建一个单独的ServiceLocator We thereby cannot share services between admin and api end-points - Singleton objects defined in both handlers are created twice. 因此,我们无法在admin和api端点之间共享服务-在两个处理程序中定义的Singleton对象都会创建两次。

Tried creating a "bridge" between the two ServiceLocators - but that causes issues with scoped resources. 试图在两个ServiceLocator之间创建“桥梁”-但这会导致范围资源的问题。 Tried creating a third ServiceLocator and bridging it to the two other locators - not good either. 尝试创建第三个ServiceLocator并将其桥接到其他两个定位器-也不好。

Any ideas how one can share DI objects between separate handlers in Jetty? 有什么想法可以在Jetty中的不同处理程序之间共享DI对象吗? Or have an alternative idea of how the above can be achieved? 或对如何实现上述目标有另一种想法?

thanks peeskillet , your suggestion indeed solved the issue 谢谢peeskillet ,您的建议确实解决了问题

ContextHandler defaultContext;
ContextHandler adminContext;
AbstractBinder sharedSingeltons;

ServiceLocator sharedServiceLocator = ServiceLocatorUtilities.bind("shared-locator", sharedSingeltons); 
defaultContext.setAttribute(ServletProperties.SERVICE_LOCATOR, sharedServiceLocator);
adminContext.setAttribute(ServletProperties.SERVICE_LOCATOR, sharedServiceLocator);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM