前端转后端:用Visual Studio Code快速搭建Spring Boot项目(含数据库配置)

前端转后端:用Visual Studio Code快速搭建Spring Boot项目(含数据库配置) 前端开发者转型指南用VS Code高效构建Spring Boot全栈项目作为一名前端开发者当你需要为自己的项目构建后端服务时Spring Boot无疑是最佳选择之一。它简化了Java开发的复杂性让你能够快速搭建起功能完善的后端系统。而Visual Studio Code作为前端开发者最熟悉的编辑器同样能胜任Spring Boot项目的开发工作。本文将带你从零开始用最熟悉的工具构建完整的后端服务。1. 环境准备与项目初始化1.1 必备工具安装在开始之前确保你的开发环境已经准备就绪Java JDKSpring Boot 3.x需要JDK 17或更高版本Visual Studio Code最新稳定版VS Code扩展Java Extension Pack提供Java语言支持Spring Boot Extension PackSpring Boot开发工具集Maven for JavaMaven项目管理支持安装完这些扩展后VS Code就变成了一个强大的Java开发环境。你可以通过CtrlShiftP打开命令面板输入Java: Configure Java Runtime来检查JDK配置是否正确。1.2 创建Spring Boot项目VS Code提供了多种创建Spring Boot项目的方式使用Spring Initializr按CtrlShiftP打开命令面板输入Spring Initializr并选择按照向导选择项目配置项目类型Maven语言JavaSpring Boot版本最新稳定版依赖项选择Web、Lombok、MyBatis等直接访问start.spring.io在浏览器中打开start.spring.io配置项目后下载zip包在VS Code中打开解压后的项目提示对于前端开发者建议选择以下依赖项Spring Web构建RESTful APILombok简化Java样板代码MyBatis Framework数据库访问Spring Boot DevTools热重载支持2. 项目结构与基础配置2.1 理解Spring Boot项目结构创建完成后你会看到如下目录结构src/ ├── main/ │ ├── java/ │ │ └── com/example/demo/ │ │ ├── DemoApplication.java │ ├── resources/ │ │ ├── static/ │ │ ├── templates/ │ │ └── application.properties └── test/ └── java/对于前端开发者来说这个结构可以类比为static/相当于前端项目的public/目录templates/服务端渲染的模板文件application.properties类似.env配置文件2.2 配置数据库连接在src/main/resources/application.properties中配置数据库连接# 数据库配置 spring.datasource.urljdbc:mysql://localhost:3306/your_database?useSSLfalseserverTimezoneUTC spring.datasource.usernameroot spring.datasource.passwordyour_password spring.datasource.driver-class-namecom.mysql.cj.jdbc.Driver # MyBatis配置 mybatis.mapper-locationsclasspath:mapper/*.xml # 服务器端口 server.port9092或者使用YAML格式创建application.ymlspring: datasource: url: jdbc:mysql://localhost:3306/your_database?useSSLfalseserverTimezoneUTC username: root password: your_password driver-class-name: com.mysql.cj.jdbc.Driver mybatis: mapper-locations: classpath:mapper/*.xml server: port: 90923. 构建RESTful API3.1 创建实体类在src/main/java/com/example/demo/entity下创建实体类import lombok.Data; Data public class Student { private int id; private String name; private int age; private String hobby; private String address; }使用了Lombok的Data注解它会自动生成getter、setter、toString等方法大大简化了Java代码。3.2 创建Mapper接口在src/main/java/com/example/demo/mapper下创建Mapper接口import java.util.List; import org.apache.ibatis.annotations.Mapper; import com.example.demo.entity.Student; Mapper public interface StudentMapper { ListStudent findAllStudent(); }3.3 创建Service层在src/main/java/com/example/demo/service下创建Service类import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.demo.entity.Student; import com.example.demo.mapper.StudentMapper; Service public class StudentService { Autowired private StudentMapper studentMapper; public ListStudent findAllStudent() { return studentMapper.findAllStudent(); } }3.4 创建Controller在src/main/java/com/example/demo/controller下创建Controller类import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.demo.entity.Student; import com.example.demo.service.StudentService; RestController RequestMapping(/api) public class StudentController { Autowired private StudentService studentService; CrossOrigin(origins *) GetMapping(/students) public ListStudent getStudents() { return studentService.findAllStudent(); } }4. 数据库操作与测试4.1 创建Mapper XML文件在src/main/resources/mapper下创建StudentMapper.xml?xml version1.0 encodingUTF-8 ? !DOCTYPE mapper PUBLIC -//mybatis.org//DTD Mapper 3.0//EN http://mybatis.org/dtd/mybatis-3-mapper.dtd mapper namespacecom.example.demo.mapper.StudentMapper select idfindAllStudent resultTypecom.example.demo.entity.Student SELECT * FROM student /select /mapper4.2 运行与测试项目在VS Code中打开DemoApplication.java点击右上角的运行按钮或按F5启动项目访问http://localhost:9092/api/students测试API如果一切正常你将看到从数据库返回的JSON数据。这与前端开发中调用API获取数据的方式完全一致只是现在你是API的提供者。5. 高级配置与优化5.1 跨域问题解决方案虽然我们已经在Controller中添加了CrossOrigin注解但在实际项目中更推荐使用全局配置import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; Configuration public class WebConfig implements WebMvcConfigurer { Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping(/api/**) .allowedOrigins(*) .allowedMethods(GET, POST, PUT, DELETE) .allowedHeaders(*); } }5.2 使用DTO优化API响应在实际项目中直接返回实体类并不是最佳实践。我们可以创建数据传输对象(DTO)import lombok.Data; Data public class StudentDTO { private String name; private int age; private String hobby; public StudentDTO(Student student) { this.name student.getName(); this.age student.getAge(); this.hobby student.getHobby(); } }然后在Service中转换public ListStudentDTO findAllStudentDTO() { return studentMapper.findAllStudent() .stream() .map(StudentDTO::new) .collect(Collectors.toList()); }5.3 异常处理创建全局异常处理器import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; ControllerAdvice public class GlobalExceptionHandler { ExceptionHandler(Exception.class) public ResponseEntityString handleException(Exception e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body(Error: e.getMessage()); } }6. 前后端协作实践6.1 接口文档生成使用Swagger生成API文档添加依赖到pom.xmldependency groupIdio.springfox/groupId artifactIdspringfox-boot-starter/artifactId version3.0.0/version /dependency创建配置类import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; Configuration public class SpringFoxConfig { Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } }访问http://localhost:9092/swagger-ui/查看API文档6.2 接口测试VS Code的REST Client扩展非常适合测试API创建src/main/resources/http/requests.http文件添加测试请求GET http://localhost:9092/api/students HTTP/1.1 Content-Type: application/json点击Send Request测试接口7. 项目打包与部署7.1 打包Spring Boot应用在VS Code中打开终端(Ctrl)运行Maven命令mvn clean package这将在target/目录下生成可执行的jar文件。7.2 运行应用java -jar target/demo-0.0.1-SNAPSHOT.jar7.3 生产环境建议使用application-prod.properties存储生产环境配置通过--spring.profiles.activeprod指定使用生产配置考虑使用Docker容器化部署FROM openjdk:17-jdk-slim COPY target/demo-0.0.1-SNAPSHOT.jar app.jar ENTRYPOINT [java,-jar,/app.jar]8. 持续学习资源作为前端开发者转型后端开发以下资源可能对你有帮助Spring官方文档spring.ioMyBatis指南mybatis.orgVS Code Java开发code.visualstudio.com/docs/languages/javaRESTful API设计restfulapi.net在实际项目中我发现将前端思维应用到后端开发中非常有帮助。例如将API端点视为前端需要的数据契约保持接口设计的简洁性和一致性。同时后端开发让我更深入地理解了数据流动和系统架构这对全栈能力的提升至关重要。