Skip to content

SpringBoot 快速开发指南

1. 项目简介

本文基于一个完整的 SpringBoot + Vue 项目模板,介绍如何快速搭建现代化的 Web 应用。

项目资源:

2. 技术栈选型

2.1 核心组件

在创建 SpringBoot 项目时,选择以下组件:

Developer Tools(开发工具):

  • GraalVM Native Support - 原生镜像支持,可将应用编译为原生可执行文件,大幅提升启动速度和降低内存占用
  • Lombok - 简化 Java 代码,自动生成 getter/setter、构造函数等

Web(Web 开发):

  • Spring Web - 提供 RESTful API 开发能力,包括 Spring MVC、Tomcat 等

SQL(数据库):

  • Spring Data JDBC - 简化的数据库访问框架
  • MyBatis - 灵活的持久层框架
  • MySQL Driver - MySQL 数据库驱动

Security(安全):

  • Spring Security - 提供认证和授权功能

2.2 额外依赖

除了 Spring Initializr 提供的组件,还需要添加以下依赖:

xml
<dependencies>
    <!-- MySQL 连接器 -->
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <scope>runtime</scope>
    </dependency>
    
    <!-- FastJSON2 - 高性能 JSON 处理库 -->
    <dependency>
        <groupId>com.alibaba.fastjson2</groupId>
        <artifactId>fastjson2</artifactId>
        <version>2.0.53</version>
    </dependency>
</dependencies>

3. 项目结构

3.1 典型的 SpringBoot 项目结构

text
src/
├── main/
│   ├── java/
│   │   └── com/
│   │       └── example/
│   │           └── demo/
│   │               ├── DemoApplication.java      # 启动类
│   │               ├── controller/               # 控制器层
│   │               │   └── UserController.java
│   │               ├── service/                  # 业务逻辑层
│   │               │   ├── UserService.java
│   │               │   └── impl/
│   │               │       └── UserServiceImpl.java
│   │               ├── mapper/                   # 数据访问层
│   │               │   └── UserMapper.java
│   │               ├── entity/                   # 实体类
│   │               │   └── User.java
│   │               ├── dto/                      # 数据传输对象
│   │               │   └── UserDTO.java
│   │               ├── vo/                       # 视图对象
│   │               │   └── UserVO.java
│   │               ├── config/                   # 配置类
│   │               │   └── SecurityConfig.java
│   │               └── utils/                    # 工具类
│   │                   └── JwtUtils.java
│   └── resources/
│       ├── application.yml                       # 配置文件
│       ├── application-dev.yml                   # 开发环境配置
│       ├── application-prod.yml                  # 生产环境配置
│       ├── mapper/                               # MyBatis 映射文件
│       │   └── UserMapper.xml
│       └── static/                               # 静态资源
└── test/                                          # 测试代码

4. 核心配置

4.1 application.yml 配置

yaml
spring:
  application:
    name: demo-app
  
  # 数据源配置
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/demo_db?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf8
    username: root
    password: password
  
  # JPA 配置
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  
  # 文件上传配置
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB

# MyBatis 配置
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.demo.entity
  configuration:
    map-underscore-to-camel-case: true

# 服务器配置
server:
  port: 8080
  servlet:
    context-path: /api

4.2 多环境配置

开发环境 application-dev.yml

yaml
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/demo_dev
logging:
  level:
    com.example.demo: DEBUG

生产环境 application-prod.yml

yaml
spring:
  datasource:
    url: jdbc:mysql://prod-server:3306/demo_prod
logging:
  level:
    com.example.demo: INFO

激活配置文件:

yaml
spring:
  profiles:
    active: dev  # 或 prod

5. 快速开发实例

5.1 实体类

java
import lombok.Data;
import java.util.Date;

@Data
public class User {
    private Long id;
    private String username;
    private String password;
    private String email;
    private Date createTime;
    private Date updateTime;
}

5.2 Mapper 接口

java
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;

@Mapper
public interface UserMapper {
    @Select("SELECT * FROM user WHERE id = #{id}")
    User findById(Long id);
    
    List<User> findAll();
    
    int insert(User user);
    
    int update(User user);
    
    int deleteById(Long id);
}

5.3 Service 层

java
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    
    public User getUserById(Long id) {
        return userMapper.findById(id);
    }
    
    public List<User> getAllUsers() {
        return userMapper.findAll();
    }
    
    public boolean createUser(User user) {
        return userMapper.insert(user) > 0;
    }
    
    public boolean updateUser(User user) {
        return userMapper.update(user) > 0;
    }
    
    public boolean deleteUser(Long id) {
        return userMapper.deleteById(id) > 0;
    }
}

5.4 Controller 层

java
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;
    
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.getUserById(id);
    }
    
    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }
    
    @PostMapping
    public boolean createUser(@RequestBody User user) {
        return userService.createUser(user);
    }
    
    @PutMapping
    public boolean updateUser(@RequestBody User user) {
        return userService.updateUser(user);
    }
    
    @DeleteMapping("/{id}")
    public boolean deleteUser(@PathVariable Long id) {
        return userService.deleteUser(id);
    }
}

6. 统一响应格式

6.1 响应实体类

java
import lombok.Data;

@Data
public class Result<T> {
    private Integer code;
    private String message;
    private T data;
    
    public static <T> Result<T> success(T data) {
        Result<T> result = new Result<>();
        result.setCode(200);
        result.setMessage("成功");
        result.setData(data);
        return result;
    }
    
    public static <T> Result<T> error(String message) {
        Result<T> result = new Result<>();
        result.setCode(500);
        result.setMessage(message);
        return result;
    }
}

6.2 使用统一响应

java
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;
    
    @GetMapping("/{id}")
    public Result<User> getUser(@PathVariable Long id) {
        User user = userService.getUserById(id);
        return Result.success(user);
    }
    
    @PostMapping
    public Result<Void> createUser(@RequestBody User user) {
        boolean success = userService.createUser(user);
        return success ? Result.success(null) : Result.error("创建失败");
    }
}

7. 异常处理

7.1 全局异常处理器

java
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    
    @ExceptionHandler(Exception.class)
    public Result<Void> handleException(Exception e) {
        e.printStackTrace();
        return Result.error("系统错误:" + e.getMessage());
    }
    
    @ExceptionHandler(IllegalArgumentException.class)
    public Result<Void> handleIllegalArgument(IllegalArgumentException e) {
        return Result.error("参数错误:" + e.getMessage());
    }
}

8. Spring Security 配置

8.1 基础安全配置

java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/public/**").permitAll()
                .anyRequest().authenticated()
            )
            .formLogin()
            .and()
            .logout();
        
        return http.build();
    }
}

9. 运行与测试

9.1 启动应用

bash
# 使用 Maven
mvn spring-boot:run

# 使用 Gradle
gradle bootRun

# 直接运行 JAR
java -jar demo-app.jar

9.2 测试 API

使用 curl 测试:

bash
# 获取用户列表
curl http://localhost:8080/api/users

# 获取单个用户
curl http://localhost:8080/api/users/1

# 创建用户
curl -X POST http://localhost:8080/api/users \
  -H "Content-Type: application/json" \
  -d '{"username":"test","password":"123456","email":"test@example.com"}'

10. 参考资料