title: Spring Boot application with H2 file database
body: <p>I'm trying to have a H2 database setup on spring boot application startup.  I have configured the database in application.properties:</p>
  
  <pre><code>spring.datasource.url = jdbc:h2:file:~/testdb
  spring.datasource.username = sa
  spring.datasource.password = sa
  spring.datasource.driverClassName = org.h2.Driver
  </code></pre>
  
  <p>The Application.java file:</p>
  
  <pre><code>@Configuration
  @ComponentScan
  @EnableAutoConfiguration
  public class Application {
      public static void main(String[] args) {
          SpringApplication.run(Application.class, args);
  
          CreateH2Database createH2Database = new CreateH2Database();
          createH2Database.create();
      }
  }
  </code></pre>
  
  <p>CreateH2Database.java:</p>
  
  <pre><code>public class CreateH2Database {
  
      private Logger log = Logger.getLogger(CreateH2Database.class);
  
      @Autowired
      protected JdbcTemplate jdbcTemplate;
  
      public void create() {
          log.info("Creating H2 Database");
          createUsers();
      }
  
      private void createUsers() {
          log.info("Creating users table");
          jdbcTemplate.execute("create table if not exists users (id serial, first_name varchar(255), last_name varchar(255))");
          String[] names = "John Woo;Jeff Dean;Josh Bloch;Josh Long".split(";");
          for (String fullname : names) {
              String[] name = fullname.split(" ");
              log.info("Inserting user record for " + name[0] + " " + name[1] + "\n");
              jdbcTemplate.update(
                  "INSERT INTO users(first_name,last_name) values(?,?)",
                  name[0], name[1]);
              }
          }
      }
  </code></pre>
  
  <p>Once the application is started it should create the Users table if it doesn't already exist, and insert the users into the table.  If the table does already exist, I don't want it to be modified.</p>
  
  <ol>
  <li>I get a <code>NullPointerException</code> on <code>jdbcTemplate.execute</code>.  How can I get the <code>jdbcTemplate</code> injected?  All the example I've seen require the datasource to be created manually, and then the JdbcTemplate is created.  However, the datasource in this example seems to be created based on the application.properties values.</li>
  <li>Is this the correct approach to setup the database (i.e. calling a <code>CreateH2Database</code> after starting the SpringApplication)?  Will this approach work if I want to run the application as a WAR on another application server?</li>
  </ol>