我有一个泽西岛端点,它使用自定义的OSGi服务ExceptionManager
服务。Jersey Endpoint + OSGi依赖关系,跟踪
@Path("service")
public class ServiceFacade {
private volatile ExceptionManager exceptionManager;
public ServiceFacade() {
BundleContext bC = FrameworkUtil.getBundle(ServiceFacade.class).getBundleContext();
ServiceReference<ExceptionManager> sR = bC.getServiceReference(ExceptionManager.class);
if (sR != null)
this.exceptionManager = bC.getService(sR);
}
@GET
@Consumes({MediaType.APPLICATION_JSON})
@Produces(MediaType.APPLICATION_JSON)
public Response sayHello() {
try {
if (exceptionManager == null)
return Response.status(Status.SERVICE_UNAVAILABLE).build();
// Do some work...
} catch (Exception e) {
exceptionManager.handle(e);
}
}
}
此泽西类添加到泽西应用程序作为一个简单的类,这意味着每次用户点击该端点,创建这个类的一个新实例来处理请求。如您所见,该类包含一个构造函数,用于初始化ExceptionManager
服务。我的问题是,是不是有一种简单的方法来检索服务,而不需要去BundleContext
?
我见过DependencyManager
,但这种捆绑似乎只依赖,加入到激活过程中的类(ServiceFacade
在这种情况下),但依赖分辨率为这做太早在运行时,每时间创建一个实例。贝娄是DependencyManager
近似,但不是一个解决方案:
public class Activator extends DependencyActivatorBase {
@Override
public void init(BundleContext bundleContext, DependencyManager dependencyManager) throws Exception {
dependencyManager.add(createComponent()
.setImplementation(ServiceFacade.class)
.add(createServiceDependency()
.setService(ExceptionManager.class)
.setRequired(true));
}
}
Thanks.-