如何使用Spring Boot正确设置JDBC控制器类?

时间:2019-02-19 00:46:56

标签: spring-boot spring-jdbc

我对Spring Boot(甚至是Spring)很陌生。我想创建一个控制我的jdbc数据库的Singleton类。在(成功的测试)之后,我尝试将主类与该DBHandler类分离,当​​我尝试在我的DBHandler类中的数据库对象上调用方法时,出现NullPointerException。
也许我需要在DBHandler类上添加一些注释?这是在Spring Boot中创建数据库处理程序类的正确方法吗?

主类:

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处理程序Singleton类,可以从其他类调用此函数。

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");
    }
}

当我拥有Autowired数据库和主(应用程序)类中的功能时,一切正常。

1 个答案:

答案 0 :(得分:1)

默认情况下,spring创建单例bean,因此将其留给spring Application上下文,并用DBHandler注释@Component

DBHandler

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

@Component
public class DBHandler {

@Autowired
JdbcTemplate database;

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");
    }
}

应用

@SpringBootApplication
public class Application implements CommandLineRunner {

@Autowired
private DBHandler dBHandler;

public static void main(String args[]) {
    SpringApplication.run(Application.class, args);
}

@Override
public void run(String... strings) throws Exception {
    db.deleteTable();
    db.createTable();
    }
 }