我正在尝试用application构造函数(继承自ResourceConfig)初始化我的Jersey应用程序中的一些组件。它看起来像这样
public Application(@Context ServletContext context,
@Context ServiceLocator locator)...当我在任何时候尝试使用定位器时,我仍然无法创建使用locator.create(MyThing.class)方法在AbstractBinder中注册的对象的实例。
我确信它们是正确绑定的,因为它们通过@inject字段注释正确地注入到我的资源类中。
不同之处在于Jersey/HK2框架正在实例化我的资源类(不出所料,因为它们在我的包扫描路径中),但我似乎无法通过代码利用ServiceLocator。
我的最终目标是在其他非jersey类具有@Inject属性时注入它们,例如。我有一个worker类,它需要注入已配置的数据库访问层。我想说
locator.Create(AWorker.class) 把它注射进去。
我如何获得真正的ServiceLocator,它将注入我已经在我的活页夹中注册/绑定的所有内容?(或者我应该使用ServiceLocator以外的其他工具?)
发布于 2014-02-25 04:28:20
您是如何启动容器的?如果你正在使用ApplicationHandler,你可以直接调用:handler.getServiceLocator()。实际上,ServiceLocator正是您想要用来访问依赖项的东西。
如果您正在启动servlet,我发现访问服务定位器的最好方法是让Jersey特性在我的启动类中设置它:
private static final class LocatorSetFeature implements Feature {
private final ServiceLocator scopedLocator;
@Inject
private LocatorSetFeature(ServiceLocator scopedLocator) {
this.scopedLocator = scopedLocator;
}
@Override
public boolean configure(FeatureContext context) {
locator = this.scopedLocator; // this would set our member locator variable
return true;
}
}该功能只需使用config.register(新的LocatorSetFeature())在我们的资源配置中注册即可。
根据容器的生命周期绑定其他组件的启动是很重要的,所以这仍然让人感觉有点老生常谈。您可以考虑将这些类作为第一类依赖项添加到HK2容器中,并简单地将适当的依赖项注入到第三方类中(例如,使用绑定器)。
发布于 2019-03-20 21:09:07
我将假设您正在启动一个servlet,并且有一个扩展org.glassfish.jersey.server.ResourceConfig的类,并且您的绑定已正确注册(例如,使用绑定器和registerInstances)。如果您想要访问ServiceLocator以执行其他初始化,您有两个选择:
一种方法是注册一个ContainerLifecycleListener (如这里的in this post所示):
// In Application extends ResourceConfig constructor
register(new ContainerLifecycleListener() {
@Override
public void onStartup(final Container container) {
// access the ServiceLocator here
final ServiceLocator serviceLocator = container.getApplicationHandler().getInjectionManager().getInstance(ServiceLocator.class);
// Perform whatever with serviceLocator
}
@Override
public void onReload(final Container container) {
/* ... */}
@Override
public void onShutdown(final Container container) {
/* ... */}
});第二种方法是使用Feature,它也可以使用@Provider自动发现
@Provider
public final class StartupListener implements Feature {
private final ServiceLocator sl;
@Inject
public ProvisionStartupListener(final ServiceLocator sl) {
this.sl = sl;
}
@Override
public boolean configure(final FeatureContext context) {
// Perform whatever action with serviceLocator
return true;
}https://stackoverflow.com/questions/21149161
复制相似问题