Posts tagged "OSGi"

CQ5.5: NullPointerException trying to reference an OSGi component/service using SCR annotations

Issue

If you are trying to reference an OSGi service or component using the SCR annotations, like the SlingRepository in the code below, then you may encounter a NullPointerException when you try to use these objects.

 /**
  * @scr.component immediate="true"
  * @scr.service interface="SampleService"
  */
 public class SampleServiceImpl implements SampleService {
     /**
      * @scr.reference
      */
     private SlingRepository repository;
...

Another symptom of this problem is that your SampleService component may not show up or register correctly in the CQ5 Web Console “components” tab (http://<server>:<port>/system/console/components).

Reason

The SCR annotations are deprecated in the latest builds of Apache Felix.

You should note that CRXDE and CRXDE Lite are both configured to automatically resolve these annotations and build the relevant XML files for you.  In other IDE environments you will have to include the maven-scr-plugin to resolve these annotations and build the XML files yourself.

Solution

To correctly reference these objects in the latest versions you should use the following syntax (note: you will have to explicitly import the Felix scr classes):

 import org.apache.felix.scr.annotations.Component;
 import org.apache.felix.scr.annotations.Service;
 import org.apache.felix.scr.annotations.Reference;

 @Component(immediate="true")
 @Service(interface="SampleService")

 public class SampleServiceImpl implements SampleService {

     @Reference
     private SlingRepository repository;
...
VN:F [1.9.22_1171]
Was this helpful? Please rate the content.
Rating: 5.0/10 (2 votes cast)