May 5, 2020
Estimated Post Reading Time ~

How to get OSGi Service object in POJO?

Overview
In AEM, OSGI Container supports dependency injection which means one OSGi service can be injected into another service using @Reference annotation. Dependency injection design is a well-known design pattern. In this post, would like to explain what are the ways to get a reference of OSGi Service?

Problems/Scenarios
As you know, In some case you are not able to get the object using @Reference annotation. Basically, the OSGi container does not allow you to inject NON-OSGi classes (POJO) into another class.

This happens when you have a class which is not registered as OSGI Component & Service. In such cases, You are left with the following option. Get the service object through a parameter to our class or get the service object through Sling request object. In Sightly model, referencing of services are possible now.

Solutions
Here is the example how to get service object through Sling request object.

// Fetching service reference from request object.
public class Example{
 public ServiceObject YouServiceReference(SlingHttpRequest request){
      final SlingBindings bindings = (SlingBindings) request.getAttribute(SlingBindings.class.getName());
      SlingScriptHelper slingScriptHelper = bindings.getSling();
     YouServiceReference service = slingScriptHelper.getService(YouServiceReference.class);
        return service
   }
}
#Wiht Sightly POJO
public class Example extends WCMUsePojo{
 public ServiceObject YouServiceReference(SlingHttpRequest request){
      return getSlingScriptHelper.getService(YouServiceReference.class);
   }
}


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.