In AEM (Adobe Experience Manager), OSGi (Open Service Gateway Initiative) services are used for modularizing code and providing functionality that can be reused across different parts of an application. OSGi services are based on the service-oriented architecture (SOA) paradigm, which promotes loose coupling and separation of concerns.
Here are the steps to create and call an OSGi service in AEM:
Create an OSGi service interface
This interface defines the methods that the OSGi service will provide. For example:
package com.example.service; public interface MyService { String getMessage(); }
Create an implementation of the OSGi service interface
This class provides the implementation of the methods defined in the OSGi service interface. For example:
package com.example.service.impl; import com.example.service.MyService; import org.osgi.service.component.annotations.Component; @Component(service = MyService.class) public class MyServiceImpl implements MyService { @Override public String getMessage() { return "Hello, World!"; } }
The @Component
annotation marks this class as an OSGi component, and the service
attribute specifies the interface that this component implements.
Register the OSGi Service
This step registers the OSGi service implementation with the OSGi container. To register the service, create an XML file in the src/main/resources/OSGI-INF
directory of your project with the following content:
<?xml version="1.0" encoding="UTF-8"?> <scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.3.0" name="My Service" immediate="true"> <implementation class="com.example.service.impl.MyServiceImpl"/> <service> <provide interface="com.example.service.MyService"/> </service> </scr:component>
This XML file specifies the component name, the implementation class, and the service interface that this component provides.
Call the OSGi Service
To call the OSGi service from your AEM code, you can use the @Reference
annotation to inject the OSGi service instance into your class. For example:
package com.example.servlets; import com.example.service.MyService; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; @Component(service = Servlet.class, property = { "sling.servlet.paths=/bin/my-servlet" }) public class MyServlet extends SlingSafeMethodsServlet { @Reference private MyService myService; @Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { response.getWriter().write(myService.getMessage()); } }
In this example, the MyServlet
class injects the MyService
instance using the @Reference
annotation, and calls the getMessage()
method of the service in the doGet()
method.
That’s it! You have now created and called an OSGi service in AEM.