I'm very new to Spring Boot (or even to Spring). I want to create a Singleton class that controls my jdbc database. After (the successfull tests) I tried to separate my main class and this DBHandler class, I get a NullPointerException when I try to call a method on my database object in my DBHandler class.
Maybe I need some annotation on my DBHandler class? Is this the proper way to create a database handler class in Spring Boot?
Main class:
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application implements CommandLineRunner {
public static void main(String args[]) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... strings) throws Exception {
DBHandler db = DBHandler.getDBHandler();
db.deleteTable();
db.createTable();
}
}
JDBC Handler Singleton class that I want to fill with functions to interact with my database that I can call from other classes.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
public class DBHandler {
@Autowired
JdbcTemplate database;
private static DBHandler instance;
private DBHandler() {
}
public static DBHandler getDBHandler() {
if (instance == null) {
synchronized (DBHandler.class) {
if (instance == null) {
instance = new DBHandler();
}
}
}
return instance;
}
public void createTable() {
database.execute("CREATE TABLE users(id SERIAL, accountName VARCHAR(255), validated VARCHAR(255), validationCode VARCHAR(255), updateDate DATETIME)");
}
public void deleteTable() {
database.execute("DROP TABLE IF EXISTS users");
}
}
Everything works fine when I have my Autowired database and the functions in the main (Application) class.