我有一個澤西島端點,它使用自定義的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.-