Importing a Service

A bundle acquires one or more imported services by simply overridding the BaseBundleActivator inherited method getImportedServices(). For example:

  protected String[] getImportedServiceNames() {
    return new String[] {
      VendorService.SERVICE_NAME,
      NapkinService.SERVICE_NAME
    };
  }

The bundle activator's activate() method will only be called once the bundle has successfully acquired all the services described by the getImportedServiceNames() method. From inside the activate() method the imported services may be accessed by calling the inherited method getImportedSerivce(String) that takes as a parameter the name of a service. For example:

  protected void activate() {
    VendorService vendor = (VendorService) getImportedService(VendorService.SERVICE_NAME);
    NapkinService napkin = (NapkinService) getImportedService(NapkinService.SERVICE_NAME);
	//...  
  }

It is often useful to write getter methods to make accessing imported services more convenient:

  private VendorService getVendorService() {
    return (VendorService) getImportedService(VendorService.SERVICE_NAME);
  }

  private NapkinService getNapkinService() {
    return (NapkinService) getImportedService(NapkinService.SERVICE_NAME);
  }

Allowing the activate() method to be a simple as:

  protected void activate() {
    VendorService vendor = getVendorService();
    NapkinService napkin = getNapkinService();
	//...  
  }