title: Java Spring - Why are autowired Repositories null in Service constructors?
body: <p>I was testing out some stuff and came across this weird behavior.</p>
  
  <p><strong>What I want to do</strong></p>
  
  <p>Let's say I want to pre-load some values into a repository using a local file, request, or whatever.</p>
  
  <p>Normally I'd put these in a constructor like this:</p>
  
  <pre><code>@Service
  public class PointOfInterestService {
  
      @Autowired
      private PointOfInterestRepository pointOfInterestRepository;
  
      public PointOfInterestService() {
          try {
              String jsonStr = Helper.isToString(new FileInputStream(new File("test.json")));
              JSONObject json = new JSONObject(jsonStr);
              JSONArray entries = json.getJSONArray("features");
              for (Object element : entries) {
                  try {      
                          //new PointOfInterest(...) 
                          //read file and do stuff
                          //... 
  
                          //finally, let's save the object
                          this.registerPointOfInterest(pointOfInterest);
                      }
                  } catch (Exception e) {
                      if (!(e instanceof JSONException)) {
                          e.printStackTrace();
                      }
                  }
  
              }
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
  
      public void registerPointOfInterest(PointOfInterest pointOfInterest) {
          pointOfInterestRepository.save(pointOfInterest);
      }
  }
  </code></pre>
  
  <p>When the constructor runs, a <code>NullPointerException</code> pops up whenever <code>registerPointOfInterest</code> is thrown.</p>
  
  <p>Using the debugger I realized that for some reason the repository is null (and thus the exception is thrown.</p>
  
  <p>This is the repository class, which is pretty simple:</p>
  
  <pre><code>package com.example.demo.PointOfInterest;
  
  import org.springframework.data.jpa.repository.JpaRepository;
  
  
  public interface PointOfInterestRepository extends JpaRepository&lt;PointOfInterest, String&gt; {
  }
  
  </code></pre>
  
  <p>Is there any easy work-around to read said file in the constructor? Thanks!</p>