AEM Solution: 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, 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);
   }
}
Advertisements


Categories: Adobe AEM, Adobe CQ, Adobe experience manager, AEM 6, AEM CMS, AEM OSGI Config, AEM Solutions, CMS, OSGI Service in POJO, OSGI Service Reference

Tags: , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.