Vertx + Jersey + HK2:使用@Contract和@Service的ServiceLocator自动绑定
我试图使用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
和@Service
HK2
注释来连接我的其他服务。
的问题是,我使用的ServiceLocatorUtilities
中,我明确地结合HK2JerseyBinder
和我的理解它,我应该只建立一个单一ServiceLocator
实例中,一切都应该是可访问/必然会已经创建ServiceLocator
。
我也知道,我可以打电话给ServiceLocatorUtilities.createAndPopulateServiceLocator()
代替,但它看起来像JerseyServer
与一切在HK2JerseyBinder
势必沿将被错过了,因为他们没有注释。
有没有一种方法可以解决这个问题?
要扩大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
的源代码。
每个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