以下是使用Spring Boot快速搭建项目脚手架的完整流程(基于Spring Boot 3.x):
一、环境准备
-
JDK 17+ (Spring Boot 3.x要求)
-
Maven 3.8+ 或 Gradle 7.x
-
IDE推荐:IntelliJ IDEA / VS Code / Eclipse
二、创建项目(3种方式)
方式1:使用 Spring Initializr
-
访问 https://start.spring.io
-
配置项目:
Project: Maven Language: Java Spring Boot: 3.3.0 Group: com.example Artifact: demo Packaging: Jar Java: 17
-
添加依赖:
-
Spring Web
-
Spring Data JPA
-
Lombok
-
MySQL Driver
-
Spring Boot DevTools
-
-
点击"Generate"下载压缩包
三、项目结构规范
src/ ├── main/ │ ├── java/ │ │ └── com/example/demo/ │ │ ├── config/ # 配置类 │ │ ├── controller/ # 控制器 │ │ ├── service/ # 服务接口 │ │ ├── impl/ # 服务实现 │ │ ├── repository/ # 数据仓库 │ │ ├── entity/ # 数据实体 │ │ ├── dto/ # 数据传输对象 │ │ ├── exception/ # 异常处理 │ │ └── DemoApplication.java # 启动类 │ └── resources/ │ ├── static/ # 静态资源 │ ├── templates/ # 模板文件 │ ├── application.yml # 主配置文件 │ └── data.sql # 初始化SQL └── test/ # 测试代码
四、核心配置
application.yml
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/demo_db?useSSL=false&serverTimezone=UTC
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
properties:
hibernate:
format_sql: true
logging:
level:
root: info
org.springframework.web: DEBUG
五、基础代码实现
实体类 (entity/User.java
)
@Data
@Entity
@NoArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(unique = true)
private String email;
}
Repository接口 (repository/UserRepository.java
)
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
}
Service层 (service/UserService.java
)
public interface UserService {
User createUser(User user);
Optional<User> getUserById(Long id);
}
ServiceImpl实现 (impl/UserServiceImpl.java
)
@Service
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
@Override
public User createUser(User user) {
return userRepository.save(user);
}
@Override
public Optional<User> getUserById(Long id) {
return userRepository.findById(id);
}
}
Controller (controller/UserController.java
)
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
return ResponseEntity.status(HttpStatus.CREATED)
.body(userService.createUser(user));
}
@GetMapping("/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
return userService.getUserById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
}
六、增强功能集成
全局异常处理 (exception/GlobalExceptionHandler.java
)
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(EntityNotFoundException.class)
public ResponseEntity<String> handleNotFound(EntityNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleValidation(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(error ->
errors.put(error.getField(), error.getDefaultMessage()));
return ResponseEntity.badRequest().body(errors);
}
}
统一响应格式 (dto/ApiResponse.java
)
@Data
public class ApiResponse<T> {
private int status;
private String message;
private T data;
public static <T> ApiResponse<T> success(T data) {
return new ApiResponse<>(200, "Success", data);
}
}
Swagger文档集成
<!-- pom.xml添加依赖 -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.5.0</version>
</dependency>
访问: http://localhost:8080/swagger-ui/index.html
七、启动与测试
启动项目
mvn spring-boot:run
# 或运行 main 方法
测试API
# 创建用户
curl -X POST http://localhost:8080/api/users \
-H "Content-Type: application/json" \
-d '{"name":"John", "email":"john@example.com"}'
# 查询用户
curl http://localhost:8080/api/users/1
git仓库地址 https://gitee.com/tianshaochen/demo.git