OSGI 获取引用service


public class ServiceUtil {

 
 
 public static <T> T getService(String className) {
  ServiceReference serviceRef = AppUtil.BUNDLECONTEXT
    .getServiceReference(className);
  Object serviceObject = AppUtil.BUNDLECONTEXT.getService(serviceRef);
  return (T) serviceObject;
 }

 
 public static <T> List<T> getServices(String className) {
  List<T> result = new ArrayList<T>();
  try {
   ServiceReference[] serviceRefs = AppUtil.BUNDLECONTEXT
     .getServiceReferences(className, null);
   for (ServiceReference serviceRef : serviceRefs) {
    Object serviceObject = AppUtil.BUNDLECONTEXT
      .getService(serviceRef);
    result.add((T) serviceObject);
   }
  } catch (InvalidSyntaxException e) {
   e.printStackTrace();
  }
  //
  return result;
 }
}

 

 

public class AppUtil {
    private static final String implClassPath = "com.xx.service.impl.AppServiceImpl";
 private static AppService appService;
 public static BundleContext BUNDLECONTEXT;
 
 public static void  setAppService(AppService appService){
  if(implClassPath.equals(appService.getClass().getName()))
      AppUtil.appService = appService;
 }
 
 public static AppService getAppService(){
  return appService;
 }
 
 public static Namespace getNamespace(String namespace){
  return appService.getNamespace(namespace);
 }
 
 public static <T> T getService(Class<T> clazz){
        ServiceReference serviceRef = BUNDLECONTEXT.getServiceReference(clazz.getName());
        Object serviceObject = BUNDLECONTEXT.getService(serviceRef);
        return (T)serviceObject;
 }
 
 public static boolean isAppServiceReady(){
     return appService==null?false:true;
 }
 
}


版权声明:本文为gaojava原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。