快学快用系列:一文学会java后端WebApi开发

快学快用系列:一文学会 Java 后端 Web API 开发(2026最新版)

Java 后端 Web API 开发的主流方式是 Spring Boot + RESTful API。Spring Boot 通过“约定大于配置”和自动装配,让你从零到一快速搭建生产级 REST 服务。2026 年推荐使用 Spring Boot 3.x / 4.x(支持 Java 21+、虚拟线程、GraalVM 原生镜像),结合 Spring Data JPALombokValidation 等,开发效率极高。

本教程采用三层架构(Controller → Service → Repository),适合企业级项目,代码清晰、可维护。

1. 准备开发环境(5 分钟搞定)

  • JDK:推荐 Java 21 或 17 LTS(Spring Boot 3.x+ 要求)。
  • 构建工具:Maven(推荐)或 Gradle。
  • IDE:IntelliJ IDEA(Community 版足够)或 VS Code + Extension。
  • 数据库:MySQL / PostgreSQL(本文用 MySQL 示例)。
  • 其他:Postman / Thunder Client 测试 API;Docker 可选(生产部署)。

创建项目(最快方式)
访问 https://start.spring.io/(Spring Initializr),选择:

  • Project:Maven
  • Language:Java
  • Spring Boot:最新稳定版(3.3+ 或 4.x)
  • Dependencies(必选):
  • Spring Web
  • Spring Data JPA
  • MySQL Driver(或 PostgreSQL Driver)
  • Lombok
  • Spring Boot DevTools(热重载)
  • Validation(参数校验)
  • Spring Security(可选,后续加 JWT)
  • 下载解压,用 IDEA 打开。

pom.xml 核心依赖(已自动生成,可手动补充):

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
</dependencies>

2. 项目结构(标准三层架构)

com.example.demo
├── DemoApplication.java          // 启动类
├── controller/                   // REST 接口层
├── service/                      // 业务逻辑层
├── repository/                   // 数据访问层
├── entity/                       // 实体类(数据库表映射)
├── dto/                          // 请求/响应 DTO(推荐)
├── exception/                    // 全局异常处理
└── config/                       // 配置类

3. 核心代码示例:用户管理 CRUD API(完整可运行)

实体类(entity/User.java)

package com.example.demo.entity;

import jakarta.persistence.*;
import lombok.Data;
import java.time.LocalDateTime;

@Entity
@Table(name = "users")
@Data  // Lombok:自动生成 getter/setter/toString 等
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    private String username;

    @Column(nullable = false)
    private String email;

    private String password;  // 实际项目需加密

    private LocalDateTime createTime = LocalDateTime.now();
}

Repository 层(repository/UserRepository.java)

package com.example.demo.repository;

import com.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByUsername(String username);
    boolean existsByEmail(String email);
}

(Spring Data JPA 自动提供 save、findAll、findById、deleteById 等方法,无需手写 SQL)

Service 层(service/UserService.java)

package com.example.demo.service;

import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    public User getUserById(Long id) {
        return userRepository.findById(id).orElseThrow(() -> new RuntimeException("User not found"));
    }

    @Transactional
    public User createUser(User user) {
        if (userRepository.existsByEmail(user.getEmail())) {
            throw new RuntimeException("Email already exists");
        }
        return userRepository.save(user);
    }

    @Transactional
    public User updateUser(Long id, User updatedUser) {
        User user = getUserById(id);
        user.setUsername(updatedUser.getUsername());
        user.setEmail(updatedUser.getEmail());
        // password 处理...
        return userRepository.save(user);
    }

    @Transactional
    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }
}

Controller 层(controller/UserController.java)—— RESTful API

package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/v1/users")  // API 版本控制
@CrossOrigin(origins = "*")  // 跨域(生产谨慎配置)
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public ResponseEntity<List<User>> getAll() {
        return ResponseEntity.ok(userService.getAllUsers());
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getById(@PathVariable Long id) {
        return ResponseEntity.ok(userService.getUserById(id));
    }

    @PostMapping
    public ResponseEntity<User> create(@Valid @RequestBody User user) {
        return new ResponseEntity<>(userService.createUser(user), HttpStatus.CREATED);
    }

    @PutMapping("/{id}")
    public ResponseEntity<User> update(@PathVariable Long id, @Valid @RequestBody User user) {
        return ResponseEntity.ok(userService.updateUser(id, user));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        userService.deleteUser(id);
        return ResponseEntity.noContent().build();
    }
}

全局异常处理(exception/GlobalExceptionHandler.java)

package com.example.demo.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> handleRuntimeException(RuntimeException ex) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage());
    }
}

配置文件(application.yml)

server:
  port: 8080

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/demo_db?useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: yourpassword
  jpa:
    hibernate:
      ddl-auto: update  # 开发用,生产用 none 或 validate
    show-sql: true

4. 运行与测试

  1. 在 MySQL 中创建数据库 demo_db
  2. 运行 DemoApplication.java(右键 → Run)。
  3. 用 Postman 测试:
  • GET http://localhost:8080/api/v1/users
  • POST http://localhost:8080/api/v1/users(Body JSON: {"username":"test","email":"test@example.com"}

常用 HTTP 方法映射

  • GET → 查询(@GetMapping)
  • POST → 创建(@PostMapping)
  • PUT/PATCH → 更新
  • DELETE → 删除

5. 进阶必备(生产级实践)

  • 参数校验@Valid + @NotBlank 等(JSR 380)。
  • 安全:Spring Security + JWT(推荐 2026 方式:无状态认证,支持虚拟线程)。
  • 文档:集成 Springdoc OpenAPI(/swagger-ui.html)。
  • 分页/排序Pageable + Specification
  • 缓存@Cacheable + Redis。
  • 日志:SLF4J + Logback。
  • 部署:Docker + Kubernetes,或 GraalVM 原生镜像(启动更快、占用更低)。
  • 测试:JUnit 5 + MockMvc / @SpringBootTest。

6. 推荐学习资源(2026 最新)

  • 官方:Spring.io Guides(REST Service)
  • 实战项目:技术派、pmhub 等开源社区系统
  • 最佳实践:Lombok + Record(Java 21+) + 不可变对象 + 统一响应封装(Result)

一句话总结
Spring Initializr 起项目 → 定义 Entity + Repository → 写 Service 业务 → Controller 暴露 REST 接口 → 加 Validation + ExceptionHandler → 跑起来测试。整个流程 30 分钟内 就能跑通一个完整 CRUD API。

想继续深入?告诉我具体需求:

  • JWT 登录认证 完整代码
  • 统一响应封装 + 分页
  • MyBatis-Plus 替代 JPA
  • Docker 部署微服务 版本
  • 完整 GitHub 可运行项目模板

直接说“我要 JWT 版”或“加分页”,我立刻给你下一部分代码!快学快用,边敲边练,半天就能上手生产级 Java Web API。🚀

文章已创建 5288

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部