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)
CQ5.5: NullPointerException trying to reference an OSGi component/service using SCR annotations, 5.0 out of 10 based on 2 ratings

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

  1. Carl Hall says:

    Be sure to enclose your annotation arguments in parentheses.

    @Component(immediate = “true”)
    @Service(interface = “SampleService”)

  2. Carsten Ziegeler says:

    While it’s true that the javadoc annotations are deprecated, they’re still supported, processed by the Maven SCR plugin and work.
    So if you have a NPE, it should have a dfferent reason than this!

  3. 2007 says:

    whoah this weblog is magnificent i really like studying your articles.

    Keep up the good work! You understand, lots of persons
    are looking round for this info, you can aid
    them greatly.