【问题标题】:NullPointerException of JDBC Template in DAO ConstructorDAO 构造函数中 JDBC 模板的 NullPointerException
【发布时间】:2021-09-10 16:03:07
【问题描述】:

我是 Spring Boot 新手,正在尝试为 Spring Boot JDBC 实现以下代码。在运行应用程序时,我在 UserDao 构造函数中的 this.jdbcTemplate 中收到 NullPointerException。我认为错误是因为在 JdbcTemplate. 的实例化之前调用了 UserDao 构造函数,对吗? 直到现在我还没有遇到这个错误,@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);
   }


}

【问题讨论】:

    标签: spring spring-boot spring-mvc autowired spring-jdbc


    【解决方案1】:

    我没有尝试运行代码,但您尝试在构造函数中使用未初始化的 jdbcTemplate 字段。 构造函数基注入应该可以解决问题

    public UserDao(JdbcTemplate jdbcTemplate) {...}
    

    否则,您仍然可以使用字段注入并将您的逻辑移动到方法中。

    public void yourMethod() {
        String query = "create table if not exists User(id int primary key, name varchar(200))";
        int update = this.jdbcTemplate.update(query);
        System.out.println("Method Called: " + update);
    }
    

    在你的情况下,它是关于 java 如何初始化类,而不是 spring boot 自动布线。

    您可以检查此answer 以了解依赖注入优先级。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-08
      • 2011-05-24
      • 1970-01-01
      • 2019-03-14
      • 2021-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多