天天看點

Spring Boot Debug 調試秘籍,日後必定有用!

背景:

Spring Boot 項目在使用 Spring Boot Maven 插件執行啟動指令 spring-boot:run 的時候,如果設定的斷點進不去,要進行以下的設定。

官方解決方案:

By default, the run goal runs your application in a forked process. If you need to debug it, you should add the necessary JVM arguments to enable remote debugging. The following configuration suspend the process until a debugger has joined on port 5005:

直接看怎麼做吧!

1、添加 JVM 參數

在插件 spring-boot-maven-plugin 裡面加上 jvmArguments 配置。

<project>
  ...
  <build>
    ...
    <plugins>
      ...
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>2.2.0.RELEASE</version>
        <configuration>
          <jvmArguments>
            -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005
          </jvmArguments>
        </configuration>
        ...
      </plugin>
      ...
    </plugins>
    ...
  </build>
  ...
</project>      

或者在指令行指定:

mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"
      
Spring Boot Debug 調試秘籍,日後必定有用!

最新配置可以參考官方說明:

https://docs.spring.io/spring-boot/docs/current/maven-plugin/examples/run-debug.html

2、添加一個Remote

在開發工具裡面新增一個 Remote 配置:
Spring Boot Debug 調試秘籍,日後必定有用!
隻需要确定 Host、Port 參數即可。
  • Host:位址
localhost:本地啟動位址;
  • Port:端口
5005:上面指令行指定的端口;

3、開始調試

先啟動加了

jvmArguments

參數的 Spring Boot 項目:
Spring Boot Debug 調試秘籍,日後必定有用!
程式停在監聽端口:5005,再 debug 啟動Remote:
Spring Boot Debug 調試秘籍,日後必定有用!
再回到項目,開始啟動輸出日志,然後就可以進行斷點調試了。
這就是遠端調試了,也能幫你 debug 遠端 Spring Boot 應用,但在本地調試要操作兩次,略顯麻煩。
未完,棧長将陸續分享 Spring Boot 最新技術教程,現在已經寫了一堆存貨了,關注微信公衆号 "Java技術棧" ,公衆号第一時間推送!