报错 | Spring报错详解

一、前言

本文主要是记录在初次学习Spring时遇到报错后的解读以及解决方案

二、报错提示

在这里插入图片描述

三、分层解读

遇到报错的时候,我们需要从下往上阅读错误,从最下面一层的Caused by开始阅读,最核心的错误是在最下面一层的;最上面 Exception in....是对下面的错误的包装

1.最下面一层Caused by

在这里插入图片描述

Caused by: java.lang.NoSuchMethodException: com.itheima.dao.impl.BookDaoImpl.

NoSuchMethodException:没有这样的方法导致的异常

在这句话后面列出了一个方法:com.itheima.dao.impl.BookDaoImpl.<init>(),也就是缺失了这个方法导致的异常报错

2.上一层Caused by

在这里插入图片描述

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.itheima.dao.impl.BookDaoImpl]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.itheima.dao.impl.BookDaoImpl.<init>()

BeanInstantiationException:Bean实例化异常

Failed to instantiate:实例化失败,在中国报错后面给了一个类com.itheima.dao.impl.BookDaoImpl,表示这个类实例化失败

扫描二维码关注公众号,回复: 17338763 查看本文章

No default constructor found:未找到默认构造函数

nested:嵌套,嵌套下一层的报错

3.最上层Caused by

在这里插入图片描述

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookDao' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.itheima.dao.impl.BookDaoImpl]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.itheima.dao.impl.BookDaoImpl.

这里我们只要看nested前的报错信息即可

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookDao' defined in class path resource [applicationContext.xml]: Instantiation of bean failed

BeanCreationException:创建Bean异常:后面写出创建哪一个Bean失败了

Error creating bean with name 'bookDao' defined in class path resource [applicationContext.xml]:在applicationContext.xml文件里名字为bookDaoBean创建失败

Instantiation of bean failed:Bean实例化失败

四、总结

这个报错原因很清晰:在 com.itheima.dao.impl.BookDaoImpl这个类中缺少默认构造函数,这里给出 com.itheima.dao.impl.BookDaoImpl类的代码


public class BookDaoImpl implements BookDao {
    
    
    public BookDaoImpl(int i) {
    
    
        System.out.println("book dao constructor is running ....");
    }
    public void save() {
    
    
        System.out.println("book dao save ...");
    }}

可以看出这里缺少不含参数的构造函数public BookDaoImpl()

五、解决方案

  1. 在原有代码上加上如下代码

    public BookDaoImpl(){
          
          
    
    	}
    
  2. 修改含参构造方法,去掉int i

    public BookDaoImpl(){
          
          
    
    	}
    

猜你喜欢

转载自blog.csdn.net/Alita233_/article/details/132165460