Search code examples
serviceinterfaceosgiaem

Why do we need a interface to define every service in aem?


I have been working with for a while but somehow never thought about this. Every aem project that I have worked on, has one similarity in their code structure. There is an interface for every service written.

My question is why do we need a interface for every service?

Can @reference or @inject not use the services without an interface?


Solution

  • Using interfaces is a good practice to decouple the user of a service from the implementation. In many cases you even want to have an API bundle so the user of the service does not need a maven dependency to the implementing bundle.

    On the other hand you are not required to use interfaces. Especially when I wire components inside a bundle interfaces are often an unnecessary layer. In this case simply export the service directly with the class.

    See here for an example:

    @Component(service = DistributionMetricsService.class)
    public class DistributionMetricsService {
    ...
    }
    

    and here for the client code:

    @Reference
    private DistributionMetricsService distributionMetricsService;
    

    So the main difference is that you have to specify the service property if you want to export a component with its implementation class.