Expand my Community achievements bar.

Learn about Edge Delivery Services in upcoming GEM session
SOLVED

Multiple implementation of a Sling Service

Avatar

Level 1

Hi experts,

   I came across a  scenario through one of my colleagues. I believe you guys can help me find solution for this issue.

   What happens if there are multiple implementations for a service interface?  

For instance consider the following interface,

 

public interface CheckService { public String getDetails(); }

and the implementations classes as follows.

Implementation1:

import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Service; @Component(enabled=true,immediate=true) @Service(value=CheckService.class) @Property(name="id",value="check1") public class CheckServiceImpl1 implements CheckService { @Override public String getDetails() { return "I am from Impl 1 - One"; } }

Implementation2:

import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Service; @Component(enabled=true,immediate=true) @Service(value=CheckService.class) @Property(name="id",value="check2") public class CheckServiceImpl2 implements CheckService { @Override public String getDetails() { return "I am from Impl 2 - Two"; } }

When i tried to invoke the service from JSP, the output i got is "I am from Impl 1 - One". I am not sure why implementation class2 didnt get invoked. It would be really helpful if you experts could provide some thoughts.

Thanks,

Jai. 

1 Accepted Solution

Avatar

Correct answer by
Level 9

Hi,

Set the OSGI service ranking. Higher Ranking service will be picked. Service ranking setting is like any other property.

Let me know if you need any other information.

Regards,

Jitendra

View solution in original post

5 Replies

Avatar

Correct answer by
Level 9

Hi,

Set the OSGI service ranking. Higher Ranking service will be picked. Service ranking setting is like any other property.

Let me know if you need any other information.

Regards,

Jitendra

Avatar

Level 1

Wow!! That is something new for me. Thank you Jitendra for the response

Avatar

Level 9

Jayapal S wrote...

Wow!! That is something new for me. Thank you Jitendra for the response

 

You are welcome.

Avatar

Level 5

Hello Jitendra,

Just curious if this is what you actually want ? With service ranking, your other service will not get picked and it defeats purpose of design to interface.

Yogesh

Avatar

Level 1

Hi Yogesh,

   If we have two different implementations for a service interface then we can define property to each implementation as some id and then use sling script helper's getService method or we can use Felix resolution to invoke the implementation that we needed.

 

   But yes, your thoughts are indeed valid even i would love to listen Jithendra's response.