Spring Boot已经成为开发web应用的标配,通过Spring Initializr创建Spring应用时,Spring Boot已经是必选项。Spring官方提供两个重要开发工具:
如果你使用的Spring Boot,那么vscode调试不是问题,已经有很好的支持。但是你可能出于学习的目的,创建的单纯Spring mvc项目,那么调试就需要一番折腾了。
安装Java Extension Pack,配置好Java开发环境。使用maven管理项目。
首先要将Spring应用运行起来,最简单的方法是通过maven插件实现,例如jetty插件,当然tomcat也是一样的。在pom.xml中加入jetty-maven-plugin,详细配置可 参考 :
<project>
<build>
<finalName>springmvc-study</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<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功能运行,配置如下:
{
// 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:
{
// 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
}
]
}
接下来就可以愉快的调试了✌。