title: Sling @Inject NullPointerError, When @Reference Successful
body: <p>When trying to <code>@Inject</code> (javax.inject.Inject) to inject <code>MyConfigurationService</code> within <code>@SlingServlet MyServlet</code> leads to a <code>NullPointerError</code> anytime any operations are attempted on <code>myConfigurationService</code> within an AEM OSGi container using Maven <code>org.apache.felix.maven-scr-plugin</code> as part of the build process.</p>
  
  <p><strong>Service Implementation:</strong></p>
  
  <pre><code>@Service({MyConfigurationService.class})
  @Component(immediate = true, metatype = true, label = "My Configuration Service")
  public class MyConfigurationServiceImpl implements MyConfigurationService {
      @Property(unbounded = PropertyUnbounded.DEFAULT, label = "API URL", description = "API URL")
      private static final String API_URL = "apiurl";
  
      private String apiUrl;
  
      @Activate
      protected void activate(Map&lt;String, Object&gt; properties) {
          this.apiUrl = PropertiesUtil.toString(properties.get(API_URL), "");
      }
  }
  </code></pre>
  
  <p><strong>Servlet:</strong></p>
  
  <pre><code>@SlingServlet(paths = "/bin/myServlet", methods = "POST", metatype = true)
  public class MyServlet extends org.apache.sling.api.servlets.SlingAllMethodsServlet {
      private static final long serialVersionUID = 1L;
      private static final Logger logger = LoggerFactory.getLogger(MyServlet.class);
  
      @Inject
      MyConfigurationService myConfigurationService;
  
      @Override
      protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServerException, IOException {
          // any attempts to use myConfigurationService results in NPE
      }
  }
  </code></pre>
  
  <p>However using <code>@Reference</code> (org.apache.felix.scr.annotations.Reference) in place of <code>@Inject</code> successfully injects the service and is usable within the <code>@SlingServlet</code> methods such as <code>doPost</code>:</p>
  
  <pre><code>@Reference
  MyConfigurationService myConfigurationService;
  </code></pre>
  
  <p>Why does <code>@Inject</code> fail to inject the service into the <code>@SlingServlet</code> when <code>@Reference</code> works?</p>
  
  <p>Thank you for any help you can provide!</p>