簡體   English   中英

Vertx + Jersey + HK2:使用@Contract和@Service的ServiceLocator自動綁定

[英]Vertx + Jersey + HK2: ServiceLocator autobindings using @Contract and @Service

我試圖利用vertx-jersey創建一個Web服務,在其中可以注入自己的自定義服務以及一些更標准的對象,例如vertx實例本身。

目前,我正在像這樣初始化Web服務器(即,遵循以下示例 ):

Vertx vertx = Vertx.vertx();
vertx.runOnContext(aVoid -> {

    JsonObject jerseyConfiguration = new JsonObject();
    // ... populate the config with base path, resources, host, port, features, etc.

    vertx.getOrCreateContext().config().put("jersey", jerseyConfiguration);

    ServiceLocator locator = ServiceLocatorUtilities.bind(new HK2JerseyBinder());

    JerseyServer server = locator.getService(JerseyServer.class);
    server.start();
});

我遇到的問題是我也希望能夠使用依賴項注入,以便可以使用@Contract@Service HK2注釋自動連接其他服務。

問題是,我已經創建ServiceLocator使用ServiceLocatorUtilities中,我明確地結合HK2JerseyBinder和我的理解它,我應該只建立一個單一的ServiceLocator中,一切都應該是可訪問/綁定實例。

我也知道我可以調用ServiceLocatorUtilities.createAndPopulateServiceLocator()來代替,但是看起來JerseyServer以及HK2JerseyBinder綁定的其他所有內容都將由於沒有注釋而被錯過。

有什么辦法可以我做到兩者兼有或如何解決?

擴展jwelll的評論:

ServiceLocatorUtilities就是它的名字所隱含的含義:它只是一個幫助創建ServiceLocator的實用程序。 要創建沒有實用程序的應用程序,可以使用ServiceLocatorFactory 這是該實用程序在調用其創建函數之一時的功能。

ServiceLocator locator = ServiceLocatorFactory().getInstance().create(null);

要將服務動態添加到定位器時,可以使用DynamicConfigurationService ,默認情況下是提供的服務。

DynamicConfigurationService dcs = locator.getService(DynamicConfigurationService.class);

該服務具有一個Populator ,您可以獲取它並調用它的populate方法,以使用居民文件中的服務填充定位器(您可以使用generator來獲取)。

Populator populator = dcs.getPopulator();
populator.populate();

這就是ServiceLocatorUtilities.createAndPopulateServiceLocator()工作

public static ServiceLocator createAndPopulateServiceLocator(String name) throws MultiException {
    ServiceLocator retVal = ServiceLocatorFactory.getInstance().create(name);

    DynamicConfigurationService dcs = retVal.getService(DynamicConfigurationService.class);
    Populator populator = dcs.getPopulator();

    try {
        populator.populate();
    }
    catch (IOException e) {
        throw new MultiException(e);
    }

    return retVal;
}

因此,由於您已經有了定位器的實例,因此您所要做的就是獲取動態配置服務,獲取populate並調用其populate方法。

ServiceLocator locator = ServiceLocatorUtilities.bind(new HK2JerseyBinder());
DynamicConfigurationService dcs = locator.getService(DynamicConfigurationService.class);
Populator populator = dcs.getPopulator();
populator.populate();

如果您想反過來做(首先是填充器),則可以

ServiceLocator locator = ServiceLocatorUtilities.createAndPopulateServiceLocator();
ServiceLocatorUtilities.bind(locator, new HK2JerseyBinder()); 

在后台,實用程序將僅使用動態配置服務。

(動態地)添加服務有很多不同的方法。 有關更多信息,請查看docs 另一個很好的信息來源是我鏈接到的ServiceLocatorUtilities的源代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM