一、前提条件
JDK、Maven已配置好
二、安装插件
Language Support for Java(TM) by Red Hat
Debugger for Java
Spring Boot Extension
Spring Boot Dashboard
3. 创建或导入Spring Boot项目
使用Spring Initializr创建新项目
- 打开命令面板(按 Ctrl+Shift+P 或 Cmd+Shift+P)。
- 输入 Spring Initializr: Generate a Maven Project 并选择该选项。
- 按照提示选择项目的配置,例如 Group、Artifact、Dependencies 等。
- 选择项目生成位置并点击“生成”。
- VSCode会提示你打开生成的项目。
导入现有项目
- 直接将项目文件夹拖到VSCode窗口中。
- VSCode会自动检测并建议你安装所需的扩展(如果还没有安装的话)。
4. 配置VSCode
配置调试环境
- 打开调试视图(点击侧栏上的虫子图标或按 Ctrl+Shift+D)。
- 点击 create a launch.json file,然后选择 Java。
- VSCode会生成一个 launch.json 文件,通常位于 .vscode 文件夹中,内容如下:
将 mainClass 和 projectName 修改为你项目的实际值。
{
"version": "0.2.0",
"configurations": [
{
"type": "java",
"name": "Debug (Launch) - Current File",
"request": "launch",
"mainClass": "${file}"
},
{
"type": "java",
"name": "Debug (Attach)",
"request": "attach",
"hostName": "localhost",
"port": 5005
},
{
"type": "java",
"name": "Debug (Launch) - MyApp",
"request": "launch",
"mainClass": "com.example.MyApp",
"projectName": "my-app"
}
]
}
5. 运行和调试项目
通过命令行运行
- 打开终端(按 Ctrl+ 或 Cmd+)。
- 导航到项目根目录。
- 运行 mvn spring-boot:run 命令启动Spring Boot应用。
通过Spring Boot Dashboard运行
- 点击侧栏上的Spring图标(Spring Boot Dashboard)。
- 在Spring Boot Dashboard中找到你的项目。
- 点击播放按钮运行项目。
通过调试模式运行
- 设置断点:在代码行号左侧点击,添加断点。
- 打开调试视图(按 Ctrl+Shift+D)。
- 选择之前配置的 Debug (Launch) - MyApp 配置。
- 点击绿色的开始按钮开始调试
6. 使用Spring Boot Actuator (可选)
如果你的项目中包含 Spring Boot Actuator,可以通过访问端点(如 /actuator/health)来监控和管理应用。
7. 配置任务自动化(可选)
你可以使用 VSCode 的任务系统来自动化构建和运行步骤:
- 创建 .vscode/tasks.json 文件。
- 添加以下配置:
{
"version": "2.0.0",
"tasks": [
{
"label": "Run Spring Boot",
"type": "shell",
"command": "mvn spring-boot:run",
"group": "build",
"problemMatcher": [],
"detail": "Runs the Spring Boot application"
}
]
}
- 你可以通过任务面板或快捷键运行此任务。