【Bug 全解决】 Java、Spring boot 后端项目 Bug 总结(持续更新中)

1,437 阅读8分钟

Bug 收集与总结

本文记录的是 SpringBoot 后端项目使用和运行代码时所遇到的各种问题,全部都已解决,欢迎在评论区补充你遇到的 Bug 哦!仅以本文记录学习社区项目时,所遇到的奇奇怪怪的 bug,以及一些很愚蠢的错误,以警醒自己不再犯同样的错误,共勉!一起进步!

请求参数定义多次,无法访问

屏幕截图_20230203_212649

出现原因:

  • 在 @RequestMapping 中已经定义 params,又在 @RequestParam 中定义 params,导致出现错误。
  • 如果参数前写了@RequestParam(xxx),并且没有添加 require = false ,那么前端必须有对应的xxx名字才行,不然,就会发生错误。
  • @RequestBody接收数据时,前端不能使用GET方式提交数据,而是用POST方式进行提交。否则也会发生错误。
  • 访问静态文件时,路径为放置在 resource/static 目录下的相对路径,如 test.html 文件在/resourse/static/html/test.html,路径即为 localhost:端口号/html/test.html,除非配置了全局url 前缀。

错误效果如下:

访问页面显示

<h1>Whitelabel Error Page</h1>
<p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p>
<div id='created'>Fri Feb 03 21:33:35 HKT 2023</div>
<div>There was an unexpected error (type=Bad Request, status=400).</div>

控制台输出

2023-02-03T21:33:35.418+08:00  INFO 24684 --- [nio-8888-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2023-02-03T21:33:35.418+08:00  INFO 24684 --- [nio-8888-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2023-02-03T21:33:35.418+08:00  INFO 24684 --- [nio-8888-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 0 ms
2023-02-03T21:33:35.430+08:00  WARN 24684 --- [nio-8888-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.UnsatisfiedServletRequestParameterException: Parameter conditions "username, password" not met for actual request parameters: ]
 

解决方案:

  • 第一种:删去 @RequestMapping 中多余的定义即可。
  • 第二种:要么添加 require = false ,要么请求添加对应参数,要么后端不加该参数
  • 第三种:使用 Post 请求,或者删去这个注解
  • 第四种:书写正确路径即可

注:System.out.printf() 为控制台输出,return、HttpServletResponse等等都是页面输出。

找不到模板文件

控制台报错:

Error resolving template template might not exist or might not be accessible;

解决方案:

  • 修改 application.yml 文件中的配置为:

    保证能够读取 html 文件,注意前有一英文半角 ”点“ ,设置 cache 为不缓存,保证实时修改,实时生效,生产环境推荐,方便调试,部署环境改为缓存型。设置文件路径,/templates 后不要加斜杆。

    spring:
      thymeleaf:
        suffix: .html
        encoding: utf-8
        mode: HTML5
        cache: false
        prefix: classpath:/template
    
  • 修改 Controller 函数访问模板路径为为相对路径,如:/demo/view ,记得最前面有斜杠,最后面没有斜杠,不需要写后缀名,默认 html

Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required

springboot 3版本整合 mybatis 3.0.5版本控制台报错 Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required,NestedIOException 这个类在 Spring 6 版本中直接删除了。对的,直接删除了。而 MyBatis 老版本还没有同步更新,所以直接就报红了。而整合 mybatis 的 mybatis-plus 自然也会报红。

2022 年 11 月26 日凌晨,mybatis-spring-boot 正式发布 3.0.0 版本,完全支持 Spring Boot 3 了。mybatis-plus 也在 2022.12.28 的 3.5.3 支持了 Spring Boot 3 。最好解决办法就是升级版本。

Could not autowire. No beans of ‘DataSource’ type found

  1. 检查项目结构,主启动类位置是否正确
  2. 把自动装配@Autowired换成@Resource

Driver com.mysql.jdbc.Driver claims to not accept jdbcUrl

该报错是配置文件路径错误,重点检查url路径,3306后的 test 为数据库名,注意修改成数据库已有数据库名

mysql8.x版本URL为 jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8

Cannot resolve method 'assertEquals' in 'Assert'

在测试方法中,使用该方法报错,没引入 import org.junit.Assert; 的Assert 包,解决方法如下:

  1. 引入 junit 依赖

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    
  2. 导入正确包 import org.junit.Assert; 的Assert

Injection of resource dependencies failed

测试方法控制台输出:Injection of resource dependencies failed

确定报错对象为 userMapper,发现没有指定 MapperScan,解决如下:

在启动类加入:@MapperScan("top.yumuing.community.mapper") 即可

Could not autowire. No beans of 'DataSource' type found.

编译报错:Could not autowire. No beans of 'DataSource' type found. 代码如下:

@Autowired
DataSource dataSource;

修改 @Autowired 为 @Resource 即可解决

FUNCTION community.count does not exist. Check the 'Function Name Parsing and Resolution' section in the Reference Manual

查询分页总页数时出现

使用如下代码出现报错:

<select id="selectDiscussPostRows" resultType="int">
    select count (id)
    from discuss_post
    where status != 2
    <if test="userId!=0">
    and user_id = #{userId}
    </if>
</select>

原因时是 count (id) 代码中,count 与 (id)存在空格,删去空格,变成count(id)即可

spirngboot 启动报duplicate key错误

错误配置:

错误配置

正确配置:

正确配置

Could not autowire. No beans of 'JavaMailSender' type found.

Incompatible types. Found: 'jakarta.mail.internet.MimeMessage', required: 'org.springframework.mail.javamail.MimeMailMessage'

错误依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
    <version>2.1.5.RELEASE</version>
<dependency> 

在 2.1.xx 版本的 spring-boot-starter-mail 使用的都是 javax,而在 2.2.xx 的版本中采用的是 Jakarta

Jakarta Mail的前生是JavaMail。JavaMail最后一个版本是于2018年8月发布,已经停止更新。新项目应该使用 Jakarta Mail。

如果混用,将会报以上错误,请勿导包错误,在 .2.xx 的版本中 ,javaMailSender.createMimeMessage() 传输的是 Jakarta

正确导包示例:springboot 3 下使用 3.0.2 版本的 spring-boot-starter-mail ,前提:配置好邮件使用

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
    <version>3.0.2</version>
<dependency> 
package top.yumuing.community.util;

import jakarta.mail.MessagingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;


@Component
public class MailClient {
    private static final Logger logger = LoggerFactory.getLogger(MailClient.class);

    @Autowired(required = false)
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String mailFrom;

    public void sendMail(String to, String subject, String content){
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
            mimeMessageHelper.setFrom(mailFrom);
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(content, true);
            javaMailSender.send(mimeMessageHelper.getMimeMessage());
            logger.info("邮件发送成功!");
        }catch (MessagingException e){
            logger.error("发送邮件失败!");
        }
    }
}

An error happened during template parsing (template: "class path resource [templates/site/register.html]"

错误配置:

spring:
  thymeleaf:
	prefix: classpath:/templates

正确配置:

spring:
  thymeleaf:
	prefix: classpath:/templates/

css、js文件配置:放置在 static 下

  • 如果首字符是“/”,则从项目的根目录开始,可以认为是项目下的绝对路径。 一般项目默认static就是根路径,所以static下的路径中不能写static,应当以 / 代替
  • 如果首字符不是“/”,而是直接以目录名开始,则以当前路径为参考系,可以认为是以当前路径为参考的相对路径
  • 使用“…/”,以当前路径为参考系的上一层路径

No primary or single unique constructor found for interface javax.servlet.http.HttpServletResponse

springboot3 下导不了 javax.servlet.http 包,必须导 jakarta.servlet.http

也就是 http 包 又更改了。

import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

不能导

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

检查字节码校验 运行不影响的警告

OpenJDK 64-Bit Server VM warning: Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.
“ OpenJDK 64位服务器VM警告:JDK 13中不建议使用选项-Xverify:none和-noverify,并且可能会在其中删除将来的版本”

-Xverify:no 或者 -noverify 这两个都是 JVM 参数,可以禁止字节码校验,提高编译速度,但是就如同警告所说,这两个参数已经过时了。现在 JVM 的运行速度已经十分迅速,无需这两个参数来加速了。

为不影响代码运行的一条警告。解决方法如下:

  • IDEA 软件下

    1. 顶部菜单下的 Run 选项中的 Edit configurations
    2. 取消勾选 Enable lanuch optimization
    3. 点击 apply 即可
  • 其他软件下

    删掉用户变量 _JAVA_OPTIONS

    根据Stack Overflow 上的帖子说,有些项目会自动将 _JAVA_OPTIONS 加到用户环境变量中,例如今天我们所讨论的警告就有可能是 _JAVA_OPTIONS 的值设置成了 -Xverify:no 或者 -noverify

依赖下载或者导入失败

  • 查找顺序:本地仓库、镜像仓库(国内)、中央仓库(国外)

  • 解决方法:

    • 设置镜像

      <!--阿里云镜像(淘宝镜像)-->
      <mirrors>
      <mirror>
      <id>nexus-aliyun</id>
      <mirrorOf>*</mirrorOf>
      <name>Nexus aliyun</name>
      <url>http://maven.aliyun.com/nexus/content/groups/public</url>;
      </mirror>
      </mirrors>
      
    • 设置私服仓库

核心配置文件不生效

目前,SpringBoot 指定的核心配置文件为 application.properties 或者 application.yml (yaml)。如果,出现拼写错误、配置文件优先级不够高或者没有放入的目录优先级不够高,被覆盖,都有可能失效。

优先级如下:

  • 同级目录下:
    • properties 高于 yaml 高于yml:后两个纯粹是执行速度导致的优先级问题。

pom文件的 spring-boot-maven-plugin报红

IDEA 在右侧的 Mave 选项卡中,点击左上角刷新即可,静待下载完成。

使用自动注入时,属性为空

  • 创建的类的没有加入@Component,没有注入;

  • 创建的类没有书写 get set 方法

  • 配置文件书写语法错误

    yaml 或 yml

    person:
      name: qinjiang
      age: 3
      happy: false
      birth: 2000/01/01
      maps: {k1: v1,k2: v2}
      lists:
       - code
       - girl
       - music
      dog:
        name: 旺财
        age: 1
    
  • @ConfigurationProperties(prefix = "image") 中 prefix 属性不匹配,即在配置文件中没有前缀为 prefix 的值。

  • 在使用方法中没有 @Autowired 实现注入 ,正确使用如下:

    @Autowired
    ImagePost image;
    

使用自定义 yaml 或 yml 实现自动注入时,属性为空

@Component
@PropertySource(value = "classpath:PostMessage.yml")
@ConfigurationProperties(prefix = "image")

查询资料可知,@PropertySource 注解目前不支持 yaml 或 yml 解析,也就是说,自定义的 yaml 或 yml 文件指定失败。故加入自定义解析类,在 main 目录下,代码如下:

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        Properties propertiesFromYaml = loadYamlIntoProperties(resource);
        String sourceName = name != null ? name : resource.getResource().getFilename();
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }

    private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException) {
                throw (FileNotFoundException) e.getCause();
            }
            throw e;
        }
    }
}

之后,修改注解 @PropertySource 的解析类,如下:

@PropertySource(value = "classpath:PostMessage.yml",factory = YamlPropertySourceFactory.class)

再次测试,成功注入。

Postman 文件无法上传

Postman 软件具有一个工作空间,所有的文件操作都是在工作空间中完成的,所以,如果出现文件上传失败,即如下情况:

image.png

出现这种情况,只需把所需文件复制到工作空间,再重新在工作空间中选中文件即可。

Spring-boot-maven-plunge 爆红

<plugins>
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
</plugins>
  • 下载失败,添加阿里云镜像
  • 加上相应的版本号