Spring Boot已经成为开发web应用的标配,通过Spring Initializr创建Spring应用时,Spring Boot已经是必选项。Spring官方提供两个重要开发工具:
- Spring Tools 4:包括eclipse、vscode和Theia三个版本,其中针对eclipse的就是之前的STS(Spring Tools Suit),是一个基于eclipse的定制版本,而针对vscode的其实就是Spring Boot Extension Pack,是一系列vscode插件。其中Spring Boot Dashboard插件提供对spring boot应用的调试支持。
- spring initializr:用于创建一个spring模板项目,目前Spring Boot是必选项。
如果你使用的Spring Boot,那么vscode调试不是问题,已经有很好的支持。但是你可能出于学习的目的,创建的单纯Spring mvc项目,那么调试就需要一番折腾了。
前提
安装Java Extension Pack,配置好Java开发环境。使用maven管理项目。
运行
首先要将Spring应用运行起来,最简单的方法是通过maven插件实现,例如jetty插件,当然tomcat也是一样的。在pom.xml中加入jetty-maven-plugin,详细配置可参考:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <project>
<build> <finalName>springmvc-study</finalName> <pluginManagement> <plugins> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.4.27.v20200227</version> <configuration> <webApp> <contextPath>/${project.build.finalName}</contextPath> </webApp> <stopKey>CTRL+C</stopKey> <stopPort>8999</stopPort> <scanIntervalSeconds>10</scanIntervalSeconds> <scanTargets> <scanTarget>src/main/webapp/WEB-INF/web.xml</scanTarget> </scanTargets> </configuration> </plugin> </plugins> </pluginManagement> </build> </project>
|
然后通过mvn jetty:run就可以运行了,而且还支持热部署,当你修改源文件后,会自动重新编译加载。
调试
调试是通过java远程调试实现的,设置maven_opts环境变量后运行mvn jetty:run或者通过vscode的task功能运行,配置如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| { // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", "tasks": [ { "label": "Jetty debug", "type": "shell", "command": "mvn jetty:run", "group": "build", "isBackground": false, "problemMatcher": [], "options": { "env": { "maven_opts": "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000" } } } ] }
|
然后在debug视图中创建launch.json:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "type": "java", "name": "Debug (Attach) - Remote", "request": "attach", "hostName": "localhost", "port": 8000 } ] }
|
接下来就可以愉快的调试了✌。