Multiple Interface Implementations - AEM/CQ - OSGi

Viewed 4860

There is an service interface HelloService, this is implemented by 2 Service implementations

HelloService Interface

public interface HelloService {
    public String getRepositoryName();
}

HelloServiceImpl1 implementation

@Service
@Component(metatype = false)
public class HelloServiceImpl1 implements HelloService {

    @Reference
    private SlingRepository repository;

    public String getRepositoryName() {
        return repository.getDescriptor(Repository.REP_NAME_DESC);
    }
}

HelloServiceimpl2 implementation

@Service
@Component(metatype = false)
public class HelloServiceImpl2 implements HelloService {

    public String getRepositoryName() {
        return "Response from HelloServiceImpl2";
    }
}

Now to use the service we use

@Reference
HelloService helloService;

Inside required method, call is made as

helloService.getRepositoryName();

I am getting response always from HelloServiceImpl1. Checked another example in AEM APIs, SlingRepository is extended by AbstractSlingRepository and AbstractSlingRepository2, how is the implementation picked internally, as while consuming we specify only @Reference SlingRepository repository;

How is this handled in AEM OSGi?


Update based on response

Checked on the syntax for this, following are observations

For using service ranking, use following with Service Implementation

@Properties({
    @Property(name = Constants.SERVICE_RANKING, intValue = 100)
})

For this no change in consumption, higher service ranking implementation is picked up, control is with provider

@Reference
HelloService helloService;

For using target filter, use following annotation to specify property

@Properties({
   @Property(name="type", value="Custom")
})

While consuming based on filter, specify target, control is with consumer

 @Reference (target="(type=Custom)")
 HelloService helloService;

If both service ranking and filter are used, filter is taking precedence.

1 Answers
Related