Search code examples
osgiaemsling

how can I use OSGI service in different package


Lets say I have Bundle A, and it has an Interface HelloWorld and function helloWorld()

Now, in another bundle B, I'm implementing as follows

@Service(HelloWorld.class)
@Component(immediate = true)
public class Test1Impl implements HelloWorld
{
  public String helloWorld()
  {
    return "I'm from Bundle B";
  }
}

I've another bundle C, I'm doing

@Service(HelloWorld.class)
@Component(immediate = true)
public class Test2Impl implements HelloWorld
{
  public String helloWorld()
  {
    return "I'm from Bundle C";
  }
}

Now if I need to get implementation of Bundle C only then what should I do? For example in general I do as below but it does not work in this case.

Helloworld obj = sling.getService(HelloWorld.class);
obj.helloWorld();

Solution

  • You can use properties and filter to choose which implementation you want to get.

    For example, you can put a property on the implementation in the bundle C :

    @Service(HelloWorld.class)
    @Component(immediate = true)
    @Property(name = "bundle", value = "bundle-c")
    public class Test2Impl implements HelloWorld { .. }
    

    then use a filter to get this implementation. you'll get an array of services matching the filter.

    HelloWorld[] services = sling.getServices(HelloWorld.class, "(bundle=bundle-c)")
    

    By default, DS put a property with the name of the component. This property is "component.id", and the name of the component is by default the full classname of the implementation. So you can use too:

    HelloWorld[] services = sling.getServices(HelloWorld.class, "(component.id=package.Test2Impl)")