title: How to resolve @Inject that gives NullPointerException?
body: <p>I have been looking for a possible solution why the @Inject object I'm using is returning null. I looked all over stackoverflow and I also bump into this site <a href="http://www.javablog.be/inject-nullpointerexception/" rel="nofollow">Solving @Inject and Null Pointer Exception</a> 
  and Im sure that Ive already taken those into consideration. </p>
  
  <p>I have a jsf file, sector.xhtml. I'm doing a file upload and calling the method upload of fileUploadController. Then the stockUploadController calls the parse method that calls the <strong>SubSectorStockParser's parse</strong> method. This method parses the uploaded csv, looping through each readline call. subSectorToStockMapping[4] is the sub sector value found in the csv file and it is being used to do a query to the database to retrieve the Subsector object. This is where the problem lies ---- the line --- </p>
  
  <pre><code>Subsector subSector = stockUploadController.findSubsector(subSectorToStockMapping[4]);
  </code></pre>
  
  <p>The stockUploadController is null eventhough it was annotated as @Inject, so it throws a NullPointerException.</p>
  
  <pre><code>21:51:57,316 INFO  [stdout] (default task-20) stockUploadController:null
  21:51:57,316 ERROR [stderr] (default task-20) java.lang.NullPointerException
  21:51:57,317 ERROR [stderr] (default task-20)   at com.traderpau.app.util.SubSectorToStockParser.parse(SubSectorToStockParser.java:45)
  21:51:57,317 ERROR [stderr] (default task-20)   at com.traderpau.app.controller.StockUploadController.parse(StockUploadController.java:42)
  21:51:57,317 ERROR [stderr] (default task-20)   at com.traderpau.app.controller.StockUploadController$Proxy$_$$_WeldClientProxy.parse(Unknown Source)
  21:51:57,318 ERROR [stderr] (default task-20)   at com.traderpau.app.controller.FileUploadController.upload(FileUploadController.java:84)
  21:51:57,318 ERROR [stderr] (default task-20)   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  21:51:57,318 ERROR [stderr] (default task-20)   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
  21:51:57,319 ERROR [stderr] (default task-20)   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  21:51:57,319 ERROR [stderr] (default task-20)   at java.lang.reflect.Method.invoke(Method.java:606)
  21:51:57,319 ERROR [stderr] (default task-20)   at com.sun.el.parser.AstValue.invoke(AstValue.java:292)
  21:51:57,320 ERROR [stderr] (default task-20)   at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
  21:51:57,320 ERROR [stderr] (default task-20)   at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
  21:51:57,320 ERROR [stderr] (default task-20)   at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
  21:51:57,321 ERROR [stderr] (default task-20)   at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
  21:51:57,321 ERROR [stderr] (default task-20)   at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
  21:51:57,321 ERROR [stderr] (default task-20)   at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
  21:51:57,322 ERROR [stderr] (default task-20)   at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
  </code></pre>
  
  <p>I have confirmed that other parts of my code that uses @Inject is working. </p>
  
  <p>Can you offer any other things that I might have missed out or any things that I can investigate to resolve this problem?</p>
  
  <h3>WEB-INF/beans.xml</h3>
  
  <pre><code> &lt;beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="
              http://xmlns.jcp.org/xml/ns/javaee
              http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd" bean-discovery-mode="all"&gt;
      &lt;/beans&gt;
  </code></pre>
  
  <h3>sector.xhtml</h3>
  
  <pre><code>&lt;html xmlns="http://www.w3.org/1999/xhtml"
        xmlns:ui="http://java.sun.com/jsf/facelets"
        xmlns:f="http://java.sun.com/jsf/core"
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:p="http://primefaces.org/ui"&gt; 
  
  &lt;h:head&gt;
  &lt;title&gt;Sector Test Entry&lt;/title&gt;
  &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;
  &lt;h:outputStylesheet name="css/screen.css" /&gt;
  &lt;/h:head&gt; 
  &lt;h:body&gt; 
      &lt;ui:composition template="/template/common/commonLayout.xhtml"&gt;
          &lt;ui:define name="content"&gt;
      &lt;div id="content"&gt;
          &lt;h:form id="transaction" enctype="multipart/form-data"&gt;
          &lt;p:growl id="growl" life="2000" /&gt;
              &lt;p:panelGrid columns="2"&gt;
  
                  &lt;p:outputLabel value="Update:"/&gt;
                  &lt;h:selectOneRadio id="update" value="#{dataUpdateBean.updateOption}"&gt;
                      &lt;f:selectItem noSelectionOption="true" itemLabel="Sector" itemValue="Sector"/&gt;
                      &lt;f:selectItem itemLabel="Sub to Stocks" itemValue="Stocks"/&gt;                    
                  &lt;/h:selectOneRadio&gt;
                  &lt;h:outputText value="&amp;#160;" /&gt;
                  &lt;p:fileUpload id="file" value="#{fileUploadController.file}" mode="simple" /&gt;
  
                  &lt;h:commandButton action="#{fileUploadController.upload}" 
                      value="Click Me" /&gt;
  
  
              &lt;/p:panelGrid&gt;
          &lt;/h:form&gt;
  
      &lt;/div&gt;
      &lt;/ui:define&gt;
      &lt;/ui:composition&gt;
  &lt;/h:body&gt; 
  &lt;/html&gt;
  </code></pre>
  
  <h3>FileUploadController.java</h3>
  
  <pre><code>import java.text.SimpleDateFormat;
  
  import javax.enterprise.inject.Model;
  import javax.faces.application.FacesMessage;
  import javax.faces.context.FacesContext;
  import javax.inject.Inject;
  import javax.servlet.http.Part;
  
  import org.primefaces.event.FileUploadEvent;
  import org.primefaces.model.UploadedFile;
  
  import com.traderpau.app.data.DataUpdateBean;
  
  @Model
  public class FileUploadController {
  
      @Inject
      private SectorUploadController sectorUploadController;
  
      @Inject 
      private StockUploadController stockUploadController;
  
      @Inject 
      private DataUpdateBean updateBean;
  
      private UploadedFile file;
  
      private Part filePart;
  
  
      public Part getFilePart() {
          return filePart;
      }
  
  
      public void setFilePart(Part filePart) {
          this.filePart = filePart;
      }
  
  
      public UploadedFile getFile() {
          return file;
      }
  
  
      public void setFile(UploadedFile file) {
          this.file = file;
      }
  
      public void saveFile(){
          System.out.println("File:" + file);
          System.out.println("File part:" + 
          filePart);
      }
  
  
      @SuppressWarnings("unused")
      public void upload() throws Exception{
          String fileName = file.getFileName();
  
          if(file != null) {
              FacesMessage message = new FacesMessage("Succesful", fileName + " is uploaded.");
              FacesContext.getCurrentInstance().addMessage(null, message);
          }else{
              FacesMessage message = new FacesMessage("Error in upload of " + fileName );
              FacesContext.getCurrentInstance().addMessage(null, message);
          }
          String path = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/");
          SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
          if(updateBean.getUpdateOption().equalsIgnoreCase("Sector")){
              file.write(
                      String.format("%s%s%s", path, "_TRADE_MONITOR_UPLOAD/SECTOR_TO_SUB/",fileName
                              ));
              sectorUploadController.parse(String.format("%s%s%s", path, "_TRADE_MONITOR_UPLOAD/SECTOR_TO_SUB/",fileName
                      ));
              FacesMessage message = new FacesMessage("Sector to Sub successdul.");
              FacesContext.getCurrentInstance().addMessage(null, message);
          }else if(updateBean.getUpdateOption().equalsIgnoreCase("Stocks")){
              file.write(
                      String.format("%s%s%s", path, "_TRADE_MONITOR_UPLOAD/SUB_TO_STOCK/",fileName
                              ));
              stockUploadController.parse(String.format("%s%s%s", path, "_TRADE_MONITOR_UPLOAD/SUB_TO_STOCK/",fileName));
              FacesMessage message = new FacesMessage("Sub to Stocks successful.");
              FacesContext.getCurrentInstance().addMessage(null, message);
          }
      }
  }
  </code></pre>
  
  <h3>StockUploadController.java</h3>
  
  <pre><code>import java.util.HashMap;
  import java.util.List;
  import java.util.Map;
  
  import javax.enterprise.inject.Model;
  import javax.faces.application.FacesMessage;
  import javax.faces.context.FacesContext;
  import javax.faces.event.ActionEvent;
  import javax.inject.Inject;
  
  import com.traderpau.app.data.DataUpdateBean;
  import com.traderpau.app.model.Stock;
  import com.traderpau.app.model.Subsector;
  import com.traderpau.app.service.StockRegistration;
  import com.traderpau.app.util.SubSectorToStockParser;
  
  @Model
  public class StockUploadController {
      @Inject
      private StockRegistration stockRegistration;
  
      @Inject
      private DataUpdateBean bean;
  
      public void findSubsectorName(ActionEvent actionEvent){
          addMessage("Search query:" + bean.getSubSectorName());
          System.out.println("StockUploadController:findSubsectorName");
          stockRegistration.findSubSectorName(bean.getSubSectorName());
      }
  
      public void addMessage(String summary) {
          FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, summary,  null);
          FacesContext.getCurrentInstance().addMessage(null, message);
      }
  
      public void parse(String filename){
  
          Map&lt;String, List&lt;String&gt;&gt; subSectorToStockMap = new HashMap&lt;&gt;();
          SubSectorToStockParser parser = new SubSectorToStockParser(subSectorToStockMap);
          parser.parse(filename);
  
      }
  
      public Subsector findSubsector(String name){
          System.out.println("StockRegistration:" + stockRegistration);
          return stockRegistration.findSubSectorName(name);
      }
  
      public void registerStock(Stock stock) throws Exception{
          stockRegistration.register(stock);
      }
  
  }
  </code></pre>
  
  <h3>SubSectorToStockParser.java</h3>
  
  <pre><code>    import java.io.BufferedReader;
      import java.io.FileNotFoundException;
      import java.io.FileReader;
      import java.io.IOException;
      import java.util.HashMap;
      import java.util.List;
      import java.util.Map;
  
      import javax.inject.Inject;
  
      import com.traderpau.app.controller.StockUploadController;
      import com.traderpau.app.model.Stock;
      import com.traderpau.app.model.Subsector;
      import com.traderpau.app.service.StockRegistration;
  
       public class SubSectorToStockParser implements Parser {
  
      private Map&lt;String, List&lt;String&gt;&gt; subSectorToStockMap = new HashMap&lt;&gt;();
  
      @Inject
      private StockRegistration stockRegistration;
  
      @Inject
      private StockUploadController stockUploadController;
  
      public SubSectorToStockParser(Map&lt;String, List&lt;String&gt;&gt; subSectorToStockMap) {
          super();
          this.subSectorToStockMap = subSectorToStockMap;
      }
  
      @Override
      public void parse(String filename) {
          System.out.println("Sub sector filename:" + filename);
          BufferedReader br = null;
          try{
              br = new BufferedReader(new FileReader(filename));
              String line;
              String csvSplitBy = ",";
              System.out.println("stockUploadController:" + stockUploadController );
  
              while((line = br.readLine()) != null){
                  String[] subSectorToStockMapping   = line.split(csvSplitBy);
                  Subsector subSector = stockUploadController.findSubsector(subSectorToStockMapping[4]);
                  Stock stock = new Stock();
                  stock.setSymbol(subSectorToStockMapping[0]);
                  stock.setStockName(subSectorToStockMapping[1]);
                  stock.setOutstandingShares( Double.parseDouble(subSectorToStockMapping[2]) );
                  stock.setSubSector(subSector != null? subSector: null);
                  stockUploadController.registerStock(stock);
              }
  
          }catch (FileNotFoundException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          } catch (Exception e) {
              e.printStackTrace();
          } finally {
              if (br != null) {
                  try {
                      br.close();
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
              }
          }
      }
  
  }
  </code></pre>