Using the OSGi Declarative Service in AEM 6.4

Understand a few project changes you might have to make in order to use these new annotations.

With the release of Adobe Experience Manager (AEM) 6.2, greater support for official OSGi Declarative Services was introduced. It’s worthwhile to consider OSGi Declarative Services implementation for your project, not just because AEM as a product is headed in that direction, but also because migration from SCR annotations is easy, and older SCR annotations are supported alongside the new ones. OSGi Declarative Services implementation will provide access to future updates and enhancements as well.

Here are the key project changes that you might have to incorporate in order to use these new annotations:

Service annotation

One of the major differences between SCR annotations and OSGI Declarative Services is in the way service references are defined.

Using SCR annotations, you can easily define a service by using the @service annotation.

OSGI Declarative Services require you to define a service reference as an attribute of the component annotation. As such, the equivalent code looks like this:

@Component(service = Servlet.class)

This also brings about a major change in the way Sling Servlets are defined using Declarative Services.

The older way of defining Sling Servlet that used to look something like this:

will now look more like this:

Service references property

Another important change is in the way service reference properties are now defined. In SCR Annotations, to define a service reference property, you might have used code that looked like this:

Here @Component(immediate = true, metatype = true, label = “Training Cleanup Service”) is used to define a Webconsole Configuration called as “Training Cleanup Service.”

This configuration contain two properties: scheduler.expression and cleanupPath, both of which are defined using the @properties annotation.

Using the OSGI Declarative Service, the equivalent code would look something like this:

Here the properties are defined with the help of an inner interface called as Config, which contains all the properties that need to defined within the web console configuration.

Properties are defined with the help of different JAVA variables, and the underscore(_) in the variable names are automatically converted into dots(.) (e.g., scheduler_expression would be mapped to scheduler.expression).

Similarly, variable names are preceded by @AttributeDefinition, which allows you to define the label and description for your properties.

@ObjectClassDefinition specifies that the upcoming inner interface contains the OSGI property definition, and @Designate is used to map the inner interface to the object class definition.