ayziba-&& 2024-06-01 19:10 采纳率: 30%
浏览 16

springboot 报错

2024-06-01 19:04:50.358 WARN 19348 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'fileController': Unsatisfied dependency expressed through field 'schoolMateServiceImpl'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'schoolMateServiceImpl': Unsatisfied dependency expressed through field 'schoolMatesMapper'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'schoolMatesMapper' defined in file [D:\Javaenvironment\workspace\mngsys\target\classes\soft3\mngsys\mapper\SchoolMatesMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method 'sqlSessionFactory' threw exception; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [D:\Javaenvironment\workspace\mngsys\target\classes\mapping\ContactMapping.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 4; columnNumber: 134; 文档根元素 "beans" 必须匹配 DOCTYPE 根 "null"。
springboot 报以上错误怎么处理,主要代码如下:


package soft3.mngsys.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import soft3.mngsys.model.SchoolMate;
import soft3.mngsys.service.SchoolMateService;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.List;

@Controller
public class FileController {
    private Model getCopyRight(Model model){
        model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
        model.addAttribute("author","则巴");
        return model;
    }
    //向文件上传页面跳转
    @GetMapping("/toUpload")
    public String fileUpload(Model model){
        getCopyRight(model);
        return "upload";
    }
    //文件上传管理
    @PostMapping("/uploadFile")
    public String uploadFile(MultipartFile[] fileUpload, Model model){
        //默认文件上传成功,并返回状态信息
        model.addAttribute("uploadStatus","上传成功!");
        for (MultipartFile file : fileUpload){
            //获取文件名以及后缀名
            String fileName = file.getOriginalFilename();
            //指定上传文件本地存储目录,不存在则需要提前创建
            String dirPath = "E:/file/";
            File filePath = new File(dirPath);
            if (!filePath.exists()){
                filePath.mkdir();
            }
            try {
                file.transferTo(new File(dirPath+fileName));
            } catch (Exception e){
                e.printStackTrace();
                //上传失败,返回失败信息
                model.addAttribute("uploadStatus","上传失败:" + e.getMessage());
            }
        }
        //携带上传状态信息回调到文件上传页面
        getCopyRight(model);
        return "upload";
    }

    @GetMapping("file_download")
    public String fileDownload(Model model){
        getCopyRight(model);
        return "download";
    }
    @GetMapping("/downloadFile")
    public ResponseEntity<byte[]> downloadFile(String filename, HttpServletRequest request) throws Exception{
        //指定被下载文件的路径
        String dirPath = "E:/file/";
        //创建文件对象
        File file = new File(dirPath + File.separator + filename);
        //设置响应头
        HttpHeaders headers = new HttpHeaders();
        //通知浏览器以下载方式打开(下载前对文件名进行转码,防止中文文件乱码)
        filename = getFilename(request,filename);
        headers.setContentDispositionFormData("attachment",filename);
        //以流的形式下载文件
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            //添加commons-io依赖
            //使用springmvc框架的ResponseEntity随心封装返回数据
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file),headers,HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseEntity<byte[]>(e.getMessage().getBytes(), HttpStatus.EXPECTATION_FAILED);
        }
    }

    //根据浏览器的不同设置,返回编码后的文件名
    private String getFilename(HttpServletRequest request,String filename) throws Exception{
        //IE不同版本User-Agent中出现的关键字
        String[] IEBrowserKeyWords = {"MSIE","Trident","Edge"};
        //获取请求的代理信息
        String userAgent = request.getHeader("User-Agent");
        for (String keyWord : IEBrowserKeyWords){
            if (userAgent.contains(keyWord)){
                //IE内核浏览器,统一为UTF-8编码显示
                return URLEncoder.encode(filename,"UTF-8").replace("+","");
            }
        }
        //火狐等其他浏览器统一为ISO-8859-1编码
        return new String(filename.getBytes("UTF-8"),"ISO-8859-1");
    }

    @Autowired
    private SchoolMateService schoolMateServiceImpl;

    @GetMapping("/all_page")
    public String all_page(Model model){
        getCopyRight(model);
        List UserList = schoolMateServiceImpl.contTable_Service();
        model.addAttribute("Result",UserList);
        return "schoolmatesList";
    }
//    public String all_page(Model model){
//        List schoolMateList = schoolMateServiceImpl.findSchoolMatesList();
//        getCopyRight(model);
//        model.addAttribute("Result",schoolMateList);
//        return "schoolmatesList";
//    }

//    @GetMapping("/countNativePlace")
//    @ResponseBody
//    public List<SchoolMate> countNativePlace(Model model){
//        getCopyRight(model);
//        List<SchoolMate> schoolMateList = schoolMateService.nativePlaceChartService();
//        model.addAttribute("Result",schoolMateList);
//        System.out.println(schoolMateList);
//        return schoolMateList;
//    }
}


package soft3.mngsys.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import soft3.mngsys.mapper.SchoolMatesMapper;
import soft3.mngsys.model.SchoolMate;


import javax.transaction.Transactional;
import java.util.List;

@Service
@Transactional
public class SchoolMateServiceImpl implements SchoolMateService{
    @Autowired
    private SchoolMatesMapper schoolMatesMapper;

    @Override
    public List contTable_Service() {
        return schoolMatesMapper.contTable();
    }
//    @Override    //重写方法
//    public List<UserInfo> findUserInfoList_Service(){
//        return userInfoMapper.findUserInfoList();
//    }
}

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" th:replace="publicPage(title='数据分页')">
<head>
    <meta charset="UTF-8">
    <title>校友录列表</title>
</head>
<body>
<div th:fragment="public_right">
    <table id="table" class="table table-hover" style="width: 80%">
        <thead>
        <th>编号</th>
        <th>姓名</th>
        <th>性别</th>
        <th>出生日期</th>
        <th>籍贯</th>
        <th>班级</th>
        <th>职务</th>
        <th>公司</th>
        </thead>
        <tbody>
        <tr class="alert-info active table-" th:each="User:${Result}">
            <td th:text="${User.id}"> </td>
            <td th:text="${User.userName}"> </td>
            <td th:text="${User.sex}"> </td>
            <td th:text="${#datas.format(User.birthday,'YYYY-MM-dd')}"> </td>
            <td th:text="${User.nativeplace}"> </td>
            <td th:text="${User.classNo}"> </td>
            <td th:text="${User.job}"> </td>
            <td th:text="${User.company}"> </td>
        </tr>
        </tbody>
    </table>
        <script type="text/javascript">
            $(document).ready(function () {
                $("#table").dataTable({
                    "bProcessing": true,               "aLengthMenu": [5, 10, 15],              "sPaginationType": "full_numbers",
                    "bAutoWidth": true,             // "bJQueryUI":true,
                    "oLanguage": {
                        "sProcessing": "正在获取数据,请稍后...",
                        "sLengthMenu": "显示 _MENU_ 条",
                        "sZeroRecords": "没有您要搜索的内容",
                        "sInfo": "从 _START_ 到 _END_ 条记录 总记录数为 _TOTAL_ 条",
                        "sInfoEmpty": "记录数为0",
                        "sInfoFiltered": "(全部记录数 _MAX_ 条)",
                        "sInfoPostFix": "",
                        "sSearch": "搜索",
                        "sUrl": "",
                        "oPaginate": {
                            "sFirst": "第一页",
                            "sPrevious": "上一页",
                            "sNext": "下一页",
                            "sLast": "最后一页"
                        }
                    },
                });
            });
        </script>


</div>

</body>
</html>

package soft3.mngsys.service;

import soft3.mngsys.model.SchoolMate;
import soft3.mngsys.model.UserInfo;

import java.util.List;

public interface SchoolMateService {
    List contTable_Service();   //数据分页
//    public List findSchoolMatesList();
}



package soft3.mngsys.mapper;

import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface SchoolMatesMapper {
    List contTable();
}

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="soft3.mngsys.mapper.SchoolMatesMapper">
    <select id="contTable" resultType="map">
        select * from schoolmates
    </select>

<!--    <select id="nativePlaceChart" resultType="map">-->
<!--        select nativeplace,count(nativeplace) as value from schoolmates group by nativeplace-->
<!--    </select>-->



</mapper>



package soft3.mngsys.model;

import java.util.Date;

public class SchoolMate {
    //Generate get and set and toString
    private Integer id;
    private String username;
    private String sex;
    private Date birthday;
    private String nativeplace;
    private String classNo;
    private String job;
    private String company;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getNativeplace() {
        return nativeplace;
    }

    public void setNativeplace(String nativeplace) {
        this.nativeplace = nativeplace;
    }

    public String getClassNo() {
        return classNo;
    }

    public void setClassNo(String classNo) {
        this.classNo = classNo;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    @Override
    public String toString() {
        return "SchoolMate{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", sex='" + sex + '\'' +
                ", birthday=" + birthday +
                ", nativeplace='" + nativeplace + '\'' +
                ", classNo='" + classNo + '\'' +
                ", job='" + job + '\'' +
                ", company='" + company + '\'' +
                '}';
    }
}

  • 写回答

3条回答 默认 最新

  • 关注

    晚上好🌙🌙🌙
    本答案参考ChatGPT-3.5

    根据错误信息分析,主要是因为FileController中的依赖注入出现问题,导致无法创建bean。具体错误包括:

    1. UnsatisfiedDependencyException: Error creating bean with name 'fileController': Unsatisfied dependency expressed through field 'schoolMateServiceImpl'fileController中的schoolMateServiceImpl字段依赖无法满足,导致无法创建bean。

    2. UnsatisfiedDependencyException: Error creating bean with name 'schoolMateServiceImpl': Unsatisfied dependency expressed through field 'schoolMatesMapper'schoolMateServiceImpl中的schoolMatesMapper字段依赖无法满足,导致无法创建bean。

    3. UnsatisfiedDependencyException: Error creating bean with name 'schoolMatesMapper' defined in file [D:\Javaenvironment\workspace\mngsys\target\classes\soft3\mngsys\mapper\SchoolMatesMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'schoolMatesMapper中的sqlSessionFactory属性依赖无法满足,导致无法创建bean。

    4. BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Bean instantiation via factory method failedsqlSessionFactory的创建失败。

    5. NestedIOException: Failed to parse mapping resource: 'file [D:\Javaenvironment\workspace\mngsys\target\classes\mapping\ContactMapping.xml]':解析ContactMapping.xml文件失败。

    6. BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 4; columnNumber: 134; 文档根元素 "beans" 必须匹配 DOCTYPE 根 "null"ContactMapping.xml文件中的根元素 <beans> 与 DOCTYPE 根 "null" 不匹配。

    为了解决这些问题,可以按照以下步骤进行处理:

    1. 检查fileControllerschoolMateServiceImpl的注入是否正确:确保SchoolMateService接口和实现类schoolMateServiceImpl都被正确地注解,并且在fileController中使用了正确的注入方式。

    2. 检查schoolMateServiceImplschoolMatesMapper的注入是否正确:确保schoolMatesMapper接口和实现类都被正确地注解,并且在schoolMateServiceImpl中使用了正确的注入方式。

    3. 检查schoolMatesMappersqlSessionFactory的注入是否正确:确保sqlSessionFactory被正确地注解,并且在schoolMatesMapper中使用了正确的注入方式。可以确认是否在配置文件中正确配置了sqlSessionFactory的bean。

    4. 检查ContactMapping.xml文件的解析是否正确:查看ContactMapping.xml文件的内容,确认使用的XML语法是否正确,并确保<beans>元素与文档声明(DOCTYPE)匹配。可以通过关闭或修改ContactMapping.xml文件中的DOCTYPE声明来解决问题。

    5. 检查与MyBatis相关的配置是否正确:确保MyBatis相关的依赖包已正确导入,并且在项目的配置文件中正确配置了MyBatis的相关信息,例如数据源、映射文件位置等。

    综上所述,根据以上错误信息,您可以按照上述步骤逐个检查和调试相关代码,排除错误并使应用正常运行。

    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 6月1日

悬赏问题

  • ¥15 校内二手商品转让网站
  • ¥20 高德地图聚合图层MarkerCluster聚合多个点,但是ClusterData只有其中部分数据,原因应该是有经纬度重合的地方点,现在我想让ClusterData显示所有点的信息,如何实现?
  • ¥100 求Web版SPC控制图程序包调式
  • ¥20 指导如何跑通以下两个Github代码
  • ¥15 大家知道这个后备文件怎么删吗,为啥这些文件我只看到一份,没有后备呀
  • ¥15 C++为什么这个代码没报错运行不出来啊
  • ¥15 一道ban了很多东西的pyjail题
  • ¥15 关于#r语言#的问题:如何将生成的四幅图排在一起,且对变量的赋值进行更改,让组合的图漂亮、美观@(相关搜索:森林图)
  • ¥15 C++识别堆叠物体异常
  • ¥15 微软硬件驱动认证账号申请