Spring boot 如何使用Spring Boot正确设置JDBC控制器类?
我对Spring Boot(甚至是Spring)非常陌生。我想创建一个控制jdbc数据库的单例类。在(成功的测试)我尝试分离我的主类和这个DBHandler类之后,当我尝试在DBHandler类中的数据库对象上调用方法时,我得到一个NullPointerException。Spring boot 如何使用Spring Boot正确设置JDBC控制器类?,spring-boot,spring-jdbc,Spring Boot,Spring Jdbc,我对Spring Boot(甚至是Spring)非常陌生。我想创建一个控制jdbc数据库的单例类。在(成功的测试)我尝试分离我的主类和这个DBHandler类之后,当我尝试在DBHandler类中的数据库对象上调用方法时,我得到一个NullPointerException。 也许我需要在我的DBHandler类上做一些注释?这是在Spring Boot中创建数据库处理程序类的正确方法吗 主要类别: import org.springframework.boot.CommandLineRunner
也许我需要在我的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处理程序单例类,我想用函数填充它,以便与我可以从其他类调用的数据库交互
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");
}
}
当我拥有我的自动连接数据库和主(应用程序)类中的函数时,一切都很好。默认情况下,spring创建单例bean,以便让spring应用程序上下文使用
@Component
注释DBHandler
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();
}
}
您是否检查了DBHandler是否为null,从而导致null指针异常?理想情况下,您不希望在DBHandler中声明静态内容,相反,您可以通过自动连接DBHandler在main类中访问数据库方法。DBHandler正在实例化,并使用打印输出函数对其进行测试。正如Deadpool在下面演示的那样,您的解决方案正是我想要的,谢谢!谢谢你的回答,这正是我想要的!现在一切都好了。