Monday, 18 March 2024

OSGi Service with filter and target in AEM

1. What happened when service interface has multiple implementation?

  • We can understand this concept for certain use cases


  • when we dealing with multiple implementations of an interface, 
  • such as a OsgiFilterDemo. For instance, 
  • let's consider having two classes: OsgiFilterDemoAImpland OsgiFilterDemoBImpl
  • Both of these classes implement methods like (getFirstName) and (getSecondName).
  • When invoking the service without explicitly specifying which implementation to use 
  • The default behavior typically refers to the original service. 
  • In this case, if no specific implementation is mentioned, OsgiFilterDemoAImpl will be called  because it has a lower service identifier compared to OsgiFilterDemoBImpl.








  • Create Dummy Component



If you want to render data in an HTML file using Sightly,





In this case, if no specific implementation is mentioned, OsgiFilterDemoAImpl will be called
because it has a lower service identifier compared to OsgiFilterDemoBImpl.



  • Suppose I want a particular implementation class, OsgiFilterDemoBImpl, to be invoked. In that case, I can define ranking using the @ServiceRanking annotation. The service with the higher ranking will be called.
  • If you want to invoke OsgiFilterDemoAImpl instead, consider giving it a higher service ranking. 




 


  • Suppose we want a specific class to be called each time, with the higher-ranking class always being invoked. However, there are times when we want either the OsgiFilterDemoAImpl or OsgiFilterDemoBImpl implementation class to be called without explicitly specifying the service ranking. In such cases, we can define a filter when calling the service, allowing us to decide whether to call OsgiFilterDemoAImpl or OsgiFilterDemoBImpl.





In other ways to implement class via Filter.









If you want to call both services in a Sling model simultaneously, you can do so.








The way you can call it in the Sling Model, but if you want to call it in a different backend module (Servlet, Scheduler, Workflow Listener, etc.), you can add a call to the OSGi service. Except for the Sling model, we can use the @Reference annotation to make the call from any other backend module. To call the classes OsgiFilterDemoAImpl or OsgiFilterDemoBImpl, you can utilize @Reference with the target parameter. By passing the target, you can define which implementation you want to call.










No comments:

Post a Comment

Servlet in AEM/Sling Servlet

  What is Servlet? A servlet is a Java class that runs on the server side where the application resides. It acts as a middle layer between t...