我是Spring Boot的新手,正试图为Spring Boot JDBC实现以下代码。在运行应用程序时,我在UserDao
构造函数中的this.jdbcTemplate
得到一个NullPointerException。我认为这个错误是因为UserDao
构造函数是在JdbcTemplate
实例化之前被调用的,这对吗?到现在为止我还没有遇到过这种错误,@Autowired
不能解决依赖关系。谁能解释一下这个错误的原因?
SpringBootDatabaseApplication.java
package com.mrityu.springbootdatabase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootDatabaseApplication {
@Autowired
private UserDao userDao;
public static void main(String[] args) {
SpringApplication.run(SpringBootDatabaseApplication.class, args);
}
}
UserDao.java
package com.mrityu.springbootdatabase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public UserDao() {
String query = "create table if not exists User(id int primary key, name varchar(200))";
int update = this.jdbcTemplate.update(query);
System.out.println("Constructor Called: " + update);
}
}
StackOverflow:spring - NullPointerException of JDBC Template in DAO Constructor - Stack Overflow