title: Getting NullPointerException with autowired Component
body: <p>Here is the class I am trying to autowire:</p>
  
  <pre><code>package com.myproject.propdrone.lib;
  
  import com.mongodb.MongoClient;
  import org.mongodb.morphia.Datastore;
  import org.mongodb.morphia.Morphia;
  import org.mongodb.morphia.mapping.MapperOptions;
  import org.springframework.stereotype.Component;
  
  @Component
  class MongoDriver {
      private final Morphia morphia;
      private final Datastore datastore;
  
      MongoDriver() {
          morphia = new Morphia();
          datastore = morphia.createDatastore(new MongoClient(), "propdrone");
          MapperOptions options = morphia.getMapper().getOptions();
          options.setStoreEmpties(true);
          options.setStoreNulls(true);
          morphia.mapPackage("com.myproject.propdrone.models");
          datastore.ensureIndexes();
      }
  
      Datastore getDatastore() {
          return datastore;
      }
  }
  </code></pre>
  
  <p>Here is the class where I am autowiring it:</p>
  
  <pre><code>package com.myproject.propdrone.lib;
  //other imports here
  @Component
  public class BuildingDataDAO {
      @Autowired
      private MongoDriver mongoDriver;
      private Datastore datastore;
      private List&lt;BuildingData&gt; allBuildingData;
  
      public BuildingDataDAO() {
          datastore = mongoDriver.getDatastore(); // THIS FAILS
          allBuildingData = getAllBuildingData();
      }
      // other class definitions
  </code></pre>
  
  <p>I am getting a <code>NullPointerException</code> thrown for the mongoDriver variable.</p>
  
  <p>The main application class sits in the package <code>com.myproject</code> and it is annotated with <code>@SpringBootApplication</code> so it should automatically scan those components. But I don't understand why it is failing.</p>
  
  <p><strong>EDIT:</strong>
  I have modified BuildingDataDTO to use a @PostConstruct but I am still facing the issue:</p>
  
  <pre><code>@PostConstruct
      private void initDatastore() {
          datastore = mongoDriver.getDatastore();
      }
  </code></pre>
  
  <p>In a different class I am instantiating BuildingDataDTO normally as:</p>
  
  <pre><code>private final BuildingDataDAO buildingDataDAO = new BuildingDataDAO();
  </code></pre>
  
  <p>and when a method is called on <em>buildingDataDAO</em> which uses datastore, I get a <em>NullPointerException</em>.</p>