[英]Vertx + Jersey + HK2: ServiceLocator autobindings using @Contract and @Service
[英]How to get HK2 ServiceLocator in Jersey 2.12?
我想創建一個類的單例實例,該類不作為資源或服務參與Jersey,但希望從Jersey ServiceLocator注入其依賴項。
我可以在我的ResourceConfig構造函數中手動注冊這個類,然后將ResourceConfig傳遞給Grizzly工廠方法,如下所示:
ResourceConfig resourceConfig = new DeviceServiceApplication();
LOGGER.info("Starting grizzly2...");
return GrizzlyHttpServerFactory.createHttpServer(BASE_URI,
resourceConfig, mServiceLocator);
剩下的問題是如何獲取對Jersey ServiceLocator的引用,以便我可以調用createAndInitialize()來獲取注入了依賴項的對象。 我在以前的Jersey版本中看到有一些構造函數變體需要ApplicationHandler,它當然提供對服務定位器的訪問(我如何初始化這是另一回事)。 您還可以看到我已嘗試傳入父ServiceLocator,但當然解決方案是從子 - >父定位器發生而不是在另一個方向,所以要求父對象失敗因為Jersey @Contract和@Service類型不是這里可見。
我是否需要使用GrizzlyHttpServerFactory以外的其他東西? 我是否放棄並手動連接我的單身依賴項?
通過注冊ContainerLifecycleListener
我能夠獲得對ServiceLocator
的引用。
在onStartup(Container container)
方法中,調用container.getApplicationHandler().getServiceLocator()
。
此示例將引用存儲為ResourceConfig
的成員變量,您可以通過訪問器在其他位置使用該變量。
class MyResourceConfig extends ResourceConfig
{
// won't be initialized until onStartup()
ServiceLocator serviceLocator;
public MyResourceConfig()
{
register(new ContainerLifecycleListener()
{
public void onStartup(Container container)
{
// access the ServiceLocator here
serviceLocator = container.getApplicationHandler().getServiceLocator();
// ... do what you need with ServiceLocator ...
MyService service = serviceLocator.createAndInitialize(MyService.class);
}
public void onReload(Container container) {/*...*/}
public void onShutdown(Container container) {/*...*/}
});
}
public ServiceLocator getServiceLocator()
{
return serviceLocator;
}
}
其他地方:
MyService service
= myResourceConfig.getServiceLocator().createAndInitialize(MyService.class);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.