Java與Spring?boot后端項目Bug超全總結(jié)
Bug 收集與總結(jié)
本文記錄的是 SpringBoot 后端項目使用和運行代碼時所遇到的各種問題,全部都已解決!僅以本文記錄學(xué)習(xí)社區(qū)項目時,所遇到的奇奇怪怪的 bug,以及一些很愚蠢的錯誤,以警醒自己不再犯同樣的錯誤,共勉!一起進(jìn)步!
請求參數(shù)定義多次,無法訪問

出現(xiàn)原因:
- 在 @RequestMapping 中已經(jīng)定義 params,又在 @RequestParam 中定義 params,導(dǎo)致出現(xiàn)錯誤。
- 如果參數(shù)前寫了@RequestParam(xxx),并且沒有添加 require = false ,那么前端必須有對應(yīng)的xxx名字才行,不然,就會發(fā)生錯誤。
- @RequestBody接收數(shù)據(jù)時,前端不能使用GET方式提交數(shù)據(jù),而是用POST方式進(jìn)行提交。否則也會發(fā)生錯誤。
- 訪問靜態(tài)文件時,路徑為放置在 resource/static 目錄下的相對路徑,如 test.html 文件在/resourse/static/html/test.html,路徑即為 localhost:端口號/html/test.html,除非配置了全局url 前綴。
錯誤效果如下:
訪問頁面顯示
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Feb 03 21:33:35 HKT 2023 There was an unexpected error (type=Bad Request, status=400).
控制臺輸出
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 ,要么請求添加對應(yīng)參數(shù),要么后端不加該參數(shù)
- 第三種:使用 Post 請求,或者刪去這個注解
- 第四種:書寫正確路徑即可
注:System.out.printf() 為控制臺輸出,return、HttpServletResponse等等都是頁面輸出。
找不到模板文件
控制臺報錯:
Error resolving template template might not exist or might not be accessible;
解決方案:
- 修改 application.yml 文件中的配置為:
保證能夠讀取 html 文件,注意前有一英文半角 ”點“ ,設(shè)置 cache 為不緩存,保證實時修改,實時生效,生產(chǎn)環(huán)境推薦,方便調(diào)試,部署環(huán)境改為緩存型。設(shè)置文件路徑,/templates 后不要加斜桿。
spring:
thymeleaf:
suffix: .html
encoding: utf-8
mode: HTML5
cache: false
prefix: classpath:/template- 修改 Controller 函數(shù)訪問模板路徑為為相對路徑,如:/demo/view ,記得最前面有斜杠,最后面沒有斜杠,不需要寫后綴名,默認(rèn) 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 正式發(fā)布 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
- 檢查項目結(jié)構(gòu),主啟動類位置是否正確
- 把自動裝配@Autowired換成@Resource
Driver com.mysql.jdbc.Driver claims to not accept jdbcUrl
該報錯是配置文件路徑錯誤,重點檢查url路徑,3306后的 test 為數(shù)據(jù)庫名,注意修改成數(shù)據(jù)庫已有數(shù)據(jù)庫名
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.導(dǎo)入正確包 import org.junit.Assert; 的Assert
Injection of resource dependencies failed
測試方法控制臺輸出:Injection of resource dependencies failed
確定報錯對象為 userMapper,發(fā)現(xiàn)沒有指定 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
查詢分頁總頁數(shù)時出現(xiàn)
使用如下代碼出現(xiàn)報錯:
<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月發(fā)布,已經(jīng)停止更新。新項目應(yīng)該使用 Jakarta Mail。
如果混用,將會報以上錯誤,請勿導(dǎo)包錯誤,在 .2.xx 的版本中 ,javaMailSender.createMimeMessage() 傳輸?shù)氖?Jakarta
正確導(dǎo)包示例: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("郵件發(fā)送成功!");
}catch (MessagingException e){
logger.error("發(fā)送郵件失敗!");
}
}
}
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 下
- 如果首字符是“/”,則從項目的根目錄開始,可以認(rèn)為是項目下的絕對路徑。
一般項目默認(rèn)static就是根路徑,所以static下的路徑中不能寫static,應(yīng)當(dāng)以 / 代替 - 如果首字符不是“/”,而是直接以目錄名開始,則以當(dāng)前路徑為參考系,可以認(rèn)為是以當(dāng)前路徑為參考的相對路徑
- 使用“…/”,以當(dāng)前路徑為參考系的上一層路徑
No primary or single unique constructor found for interface javax.servlet.http.HttpServletResponse
springboot3 下導(dǎo)不了 javax.servlet.http 包,必須導(dǎo) jakarta.servlet.http
也就是 http 包 又更改了。
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession;
不能導(dǎo)
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;
檢查字節(jié)碼校驗 運行不影響的警告
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位服務(wù)器VM警告:JDK 13中不建議使用選項-Xverify:none和-noverify,并且可能會在其中刪除將來的版本”
-Xverify:no 或者 -noverify 這兩個都是 JVM 參數(shù),可以禁止字節(jié)碼校驗,提高編譯速度,但是就如同警告所說,這兩個參數(shù)已經(jīng)過時了。現(xiàn)在 JVM 的運行速度已經(jīng)十分迅速,無需這兩個參數(shù)來加速了。
為不影響代碼運行的一條警告。解決方法如下:
- IDEA 軟件下
- 頂部菜單下的 Run 選項中的 Edit configurations
- 取消勾選 Enable lanuch optimization
- 點擊 apply 即可
- 其他軟件下
刪掉用戶變量 _JAVA_OPTIONS
根據(jù)Stack Overflow 上的帖子說,有些項目會自動將 _JAVA_OPTIONS 加到用戶環(huán)境變量中,例如今天我們所討論的警告就有可能是 _JAVA_OPTIONS 的值設(shè)置成了 -Xverify:no 或者 -noverify
依賴下載或者導(dǎo)入失敗
查找順序:本地倉庫、鏡像倉庫(國內(nèi))、中央倉庫(國外)
解決方法:
設(shè)置鏡像
<!--阿里云鏡像(淘寶鏡像)--> <mirrors> <mirror> <id>nexus-aliyun</id> <mirrorOf>*</mirrorOf> <name>Nexus aliyun</name> <url>http://maven.aliyun.com/nexus/content/groups/public</url>; </mirror> </mirrors>
設(shè)置私服倉庫
核心配置文件不生效
目前,SpringBoot 指定的核心配置文件為 application.properties 或者 application.yml (yaml)。如果,出現(xiàn)拼寫錯誤、配置文件優(yōu)先級不夠高或者沒有放入的目錄優(yōu)先級不夠高,被覆蓋,都有可能失效。
優(yōu)先級如下:
- 同級目錄下:
- properties 高于 yaml 高于yml:后兩個純粹是執(zhí)行速度導(dǎo)致的優(yōu)先級問題。
pom文件的 spring-boot-maven-plugin報紅
IDEA 在右側(cè)的 Mave 選項卡中,點擊左上角刷新即可,靜待下載完成。
使用自動注入時,屬性為空
- 創(chuàng)建的類的沒有加入@Component,沒有注入;
- 創(chuàng)建的類沒有書寫 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 實現(xiàn)注入 ,正確使用如下:
@Autowired ImagePost image;
使用自定義 yaml 或 yml 實現(xiàn)自動注入時,屬性為空
@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 軟件具有一個工作空間,所有的文件操作都是在工作空間中完成的,所以,如果出現(xiàn)文件上傳失敗,即如下情況:

出現(xiàn)這種情況,只需把所需文件復(fù)制到工作空間,再重新在工作空間中選中文件即可。
Spring-boot-maven-plunge 爆紅
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>下載失敗,添加阿里云鏡像加上相應(yīng)的版本號
總結(jié)
到此這篇關(guān)于Java與Spring boot后端項目Bug超全總結(jié)的文章就介紹到這了,更多相關(guān)Java后端項目Bug內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
搭建 springboot selenium 網(wǎng)頁文件轉(zhuǎn)圖片環(huán)境的詳細(xì)教程
這篇文章主要介紹了搭建 springboot selenium 網(wǎng)頁文件轉(zhuǎn)圖片環(huán)境,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-08-08
Linux中Java開發(fā)常用軟件安裝方法總結(jié)
這篇文章主要介紹了Linux中Java開發(fā)常用軟件安裝方法總結(jié),需要的朋友可以參考下2020-02-02

