1. 程式人生 > 程式設計 >SpringBoot專案中遇到的BUG問題及解決方法

SpringBoot專案中遇到的BUG問題及解決方法

1.啟動專案的時候報錯

1.Error starting ApplicationContext.
To display the auto-configuration report re-run your application with 'debug' enabled.

解決方法:

在yml配置檔案中加入debug: true,因為預設的話是false

2.在整合mybatis時mapper包中的類沒被掃描

org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'com.app.mapper.UserMapper' available:

expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

解決方法:

在springboot的啟動類中加入@MapperScan("mapper類的路徑")
或者直接在Mapper類上面添加註解@Mapper,建議使用上面那種,不然每個mapper加個註解也挺麻煩的

3.在向資料庫插入資料時報錯

"\r\n### Error updating database. Cause:
com.mysql.jdbc.MysqlDataTruncation:
Data truncation: Data too long for column 'password' at row 1\r\n###

資料庫表password這個欄位太短了,應該設長點

java.lang.ClassCastException: 
com.app.entity.User cannot be cast to java.lang.Integer

4.用mybatis查詢時報錯

org.mybatis.spring.MyBatisSystemException: 
nested exception is org.apache.ibatis.binding.BindingException: 
Parameter 'user_type' not found. Available parameters are [2,1,param1,param2,param3]

原因:@Param註解缺失,當只有一個引數時,Mapper介面中可以不使用

public User getUser(String name);

有多個引數時就必須使用

public User getUser(@Param("name") String name,@Param("password") String password); 

5.Mybatis查詢傳入一個字串傳引數報錯

mapper介面:
PkRecord findByPkStudentNumber(String pkStudentNumber);
對應的mapper配置檔案
<select id="findByPkStudentNumber" resultMap="recordMap" >
 SELECT * FROM pk_record
 <where>
 <if test="pkStudentNumber!=null">
 pk_student_number=#{pkStudentNumber}
 </if>
 </where>
 </select>

然後就會報如下錯誤

There is no getter for property named 'XXX' in 'class java.lang.String'

原因:

Mybatis預設採用ONGL解析引數,所以會自動採用物件樹的形式取string.num值,引起報錯。

解決方法:

①在mapper配置檔案中引數名,都要改成_parameter

<select id="findByPkStudentNumber" resultMap="recordMap" >
 SELECT * FROM pk_record
 <where>
 <if test="_parameter!=null">
 pk_student_number=#{_parameter}
 </if>
 </where>
 </select>

②在mapper介面中用@Param在相關方法說明引數值

PkRecord findByPkStudentNumber(@Param("pkStudentNumber") String pkStudentNumber);

6.mybatis返回值報錯

org.apache.ibatis.binding.BindingException: 
Mapper method 'com.hoomsun.mybatis.dao.CostMapperDao.dongtaislq' 
has an unsupported return type: class java.lang.String

dao介面類中對應的方法去掉返回值,用void,例如:

public void dongtaislq(Map map);

7.mybatis中集合與Stirng型別的比較

報錯資訊

invalid comparison: java.util.ArrayList and java.lang.String

原因:無法比較這兩種型別

<if test="categoryIds!=null and categoryIds!=' ' ">
 AND category_id IN
 <foreach collection="categoryIds" item="categoryIds" open="(" separator="," close=")">
 #{categoryIds}
 </foreach>
</if>

在接收list的時候加了判斷 list !=' ',引起了集合與Stirng型別的比較,所以報錯,將判斷條件改為 : list.size >0就可以了

<if test="categoryIds!=null and categoryIds.size>0" >
 AND category_id IN
 <foreach collection="categoryIds" item="categoryIds" open="(" separator="," close=")">
 #{categoryIds}
 </foreach>
</if>

8.儲存物件資料進資料庫後根據ID查詢並返回該物件時為null

<insert id="saveUser" useGeneratedKeys="true" keyColumn="id" >
 insert into user(username,password,nickname) values (#{username},#{password},#{nickname})
</insert>

這樣寫的話資料可以儲存到資料庫,沒問題,ID也可以自動增長,不過儲存後立刻根據ID查詢時返回會為null
解決的方法是把keyColumn換成keyProperty就可以了

<insert id="saveUser" useGeneratedKeys="true" keyProperty="id" >
 insert into user(username,#{nickname})
</insert>

9.idea執行專案時報錯

//子容器啟動失敗
ERROR 8760 --- [cat-startStop-1] org.apache.catalina.core.ContainerBase : A child container failed during start
//未能啟動Tomcat元件
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: 
Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]]

這裡的問題主要是jre環境沒選好,可能是由於你之前專案要求改變jre,然後導致之前的專案jre環境也改變了。

idea具有內建tomcat,所以可以不用額外配置tomcat

在idea中點選執行→編輯結構→在配置中選擇jre環境

我這裡是選用1.8的環境

SpringBoot專案中遇到的BUG問題及解決方法

Paste_Image.png

再次啟動專案:

SpringBoot專案中遇到的BUG問題及解決方法

Paste_Image.png

啟動成功了

10.mybatis插入資料時預設值不生效

插入語句

<insert id="insert" useGeneratedKeys="true" keyProperty="id">
 insert into mmall_category (id,name,status)
 values (#{id},#{name},#{status})
 </insert>

對應的mapper

void insert(Category category);

需要傳入的是一個物件,假如你在資料庫設計時把status設定預設值
在傳入物件時只賦值給name,結果你可以發現數據庫中status的值是null

這是因為這個物件的其他屬性成員你不賦值的話預設為null,並且你在sql語句中#{status},也就是把null賦給了status,但是有時候有需要傳status,不能把#{status}去掉,那該怎麼辦呢?
解決方法:

<insert id="insert" useGeneratedKeys="true" keyProperty="id">
 insert into mmall_category 
 (id,name
 <if test="status != null">,status
 </if>)
 values (#{id},#{name}
 <if test="status != null">,#{status}
 </if>)
 </insert>

使用mybatis的if test進行值的判斷,如果是null的話就不賦值

mybatis的高階結果對映

association – 一個複雜的型別關聯;許多結果將包成這種型別
嵌入結果對映 – 結果對映自身的關聯,或者參考一個

看起來挺難懂的,看下例項
在resultMap中,有這樣的一個對映

<association property="user" column="user_id" select="com.mapper.UserMapper.selectByPrimaryKey"/>

當你用select查詢出來物件時想獲取userId的值要先獲取對映的物件再獲取其ID,不然直接獲取userId會為空

11.InterlliJ Debug方式啟動特別慢

Method breakpoints may dramatically slow down debugging

不管你是重啟伺服器和重啟idea還是報這個問題。由該提示語我們可以知道要把方法斷點給關掉,檢視斷點的快捷方式是Ctrl + Shift +F8

SpringBoot專案中遇到的BUG問題及解決方法

Java Method Breakpoints去掉即可

錯誤Caused by: java.lang.IllegalStateException: In the composition of all global method configuration,no annotation support was actually activated

原因:在所有全域性方法配置的組合中,實際上沒有啟用註釋支援

解決方法:

在啟動類中加入@EnableGlobalMethodSecurity(securedEnabled = true)

@SpringBootApplication
@EnableGlobalMethodSecurity(securedEnabled = true)
public class Application {
 public static void main(String[] args) {
 SpringApplication.run(Application.class,args);
 }
}

12.MyBatis繫結錯誤

Invalid bound statement (not found)

這個錯誤主要是因為mapper介面與mapper.xml的路徑沒有一一對應,並且mapper.xml不能放在src目錄裡,配置檔案必須放resources裡,src目錄下的xml檔案預設不會編譯到target

13.使用請求轉發或者重定向出現異常

java.lang.IllegalStateException: Cannot forward after response has been committed

原因:

報異常的原因是重複轉發或者重定向了請求

解決方法:

如果有多個轉發或者重定向,需要在每個轉發或者重定向請求之後加上return語句(最後一個請求轉發或者重定向可以不加)

14.SpringBoot配置資料庫連線池,但日誌卻每次都新建連線

Mybatis中動態列印SQL語句到控制檯,只需要在SpringBoot配置檔案中新增如下配置即可

mybatis:
 configuration:
 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

但是如果沒有用到任何連線池的話,是不會列印的

Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2a5ca7d7] was not 
registered for synchronization because synchronization is not active
JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@9a51d74] will not be managed by Spring
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2a5ca7d7]

解決方法:

確保有可用的連線池被使用,引入第三方連線池要做好配置

15.SpringBoot專案中service層互相引用

Description:
The dependencies of some of the beans in the application context form a cycle:
 xxxController (field private aaaService xxxController.aaaService)
┌─────┐
| aaaImpl defined in file [aaaImpl.class]
↑ ↓
| bbbImpl (field private aaaService bbbImpl.orderService)
└─────┘

解決方法:

注入方式用的是@RequiredArgsConstructor 註解final方式注入報錯
將注入方式改為@Autowired成功解決

16.SpringBoot配置檔案中使用了過時的配置項

Caused by: org.springframework.boot.context.properties.bind.UnboundConfigurationPropertiesException:
The elements [spring.resources.chain.gzipped] were left unbound.

已廢棄的配置項

spring:
 resources:
 chain:
 gzipped: true

解決方法:刪掉過期的配置項即可

到此這篇關於SpringBoot專案中遇到的BUG問題及解決方法的文章就介紹到這了,更多相關SpringBoot專案遇到bug內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!