3

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();
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
  • What does "it does not work" mean? This provides no information. Please state what you expected to happen, and what actually happened. – Neil Bartlett Mar 11 '16 at 18:02
  • @NeilBartlett, I mean I do not get the desired result "I'm from Bundle C" instead i get "i'm from Bundle B", i guess this is happening because Bundle B was resolved first. – Sumanta Pakira Mar 12 '16 at 07:33
  • No it has nothing to do with who resolves first. You can get either of the implementations because they are both equally valid matches for the service interface you are requesting. – Neil Bartlett Mar 12 '16 at 08:22

1 Answers1

5

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)")
Jérémie B
  • 10,611
  • 1
  • 26
  • 43