2017-08-27 125 views
0

我試圖使用vertx-jersey創建一個web服務,我可以在其中注入自己的自定義服務以及一些更多的標準對象,如vertx實例本身。Vertx + Jersey + HK2:使用@Contract和@Service的ServiceLocator自動綁定

在我初始化的網絡服務器,像這樣的時刻(即以下this example):

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@ServiceHK2註釋來連接我的其他服務。

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

我也知道,我可以打電話給ServiceLocatorUtilities.createAndPopulateServiceLocator()代替,但它看起來像JerseyServer與一切在HK2JerseyBinder勢必沿將被錯過了,因爲他們沒有註釋。

有沒有一種方法可以解決這個問題?

+1

每個ServiceLocator都有一個綁定到其中的DynamicConfigurationService(https://javaee.github.io/hk2/apidocs/org/glassfish/hk2/api/DynamicConfigurationService.html)。從中你可以得到一個Populator(https://javaee.github.io/hk2/apidocs/org/glassfish/hk2/api/Populator.html)。 populator的方法可以用來動態地添加(例如)居民文件或類掃描的服務,或者從您希望用來發現服務的其他自動機制中動態添加服務。 – jwells131313

回答

1

要擴大jwelll的評論:

ServiceLocatorUtilities正是它的名字所暗示的:它只是一個工具來幫助創建ServiceLocator。要在沒有公用程序的情況下創建它,您可以使用ServiceLocatorFactory。這是實用程序在調用其創建函數之一時所做的工作。

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

當你想服務動態地定位添加,你可以使用DynamicConfigurationService,這是默認提供的服務。

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

該服務有一個Populator,你可以得到,並調用它populate方法,它從填充服務定位器的inhabitant files(你可以得到這些與generator)。

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

這是所有的ServiceLocatorUtilities.createAndPopulateServiceLocator() does

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方法。

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

引擎蓋下,公用事業將只使用動態配置的服務。

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