1. 创建一个 Spring Boot 项目
你可以通过 Spring Initializr 网站生成一个 Spring Boot 项目,也可以通过命令行工具或 IDE(如 IntelliJ IDEA 或 Eclipse)创建。
- 在 Spring Initializr 网站中选择项目的基本设置:
- Project: Maven Project
- Language: Java
- Spring Boot Version: 最新稳定版(如 3.x.x)
- Dependencies: 选择 Spring Web
点击“Generate”生成项目,然后解压下载的文件并导入到你的 IDE 中。
2. 项目结构
一个典型的 Spring Boot 项目结构如下:
src
│ ├── main
│ │ ├── java
│ │ │ └── com.example.demo
│ │ │ ├── DemoApplication.java # 启动类
│ │ │ ├── controller
│ │ │ │ └── UserController.java # 控制器类
│ │ │ ├── service
│ │ │ │ └── UserService.java # 服务类
│ │ │ ├── model
│ │ │ │ └── User.java # 实体类
│ │ │ ├── repository
│ │ │ └── UserRepository.java # 数据库访问类
│ │ └── resources
│ │ ├── application.properties # 配置文件
3. 编写实体类
在 model
包下创建一个实体类 User.java
:
package com.example.demo.model;
public class User {
private Long id;
private String name;
private String email;
// Getters and Setters
}
4. 创建控制器类
在 controller
包下创建一个控制器类 UserController.java
:
package com.example.demo.controller;
import com.example.demo.model.User;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
private List<User> users = new ArrayList<>();
@GetMapping
public List<User> getAllUsers() {
return users;
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return users.stream().filter(user -> user.getId().equals(id)).findFirst().orElse(null);
}
@PostMapping
public User createUser(@RequestBody User user) {
users.add(user);
return user;
}
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User updatedUser) {
User user = getUserById(id);
if (user != null) {
user.setName(updatedUser.getName());
user.setEmail(updatedUser.getEmail());
}
return user;
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
users.removeIf(user -> user.getId().equals(id));
}
}
5. 启动应用程序
在 DemoApplication.java
中启动应用程序:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
6. 运行和测试
运行项目后,API 将在 http://localhost:8080
上启动。你可以通过 Postman
、cURL
或浏览器访问以下 URL 进行测试:
GET /api/users
- 获取所有用户GET /api/users/{id}
- 根据 ID 获取用户POST /api/users
- 创建新用户PUT /api/users/{id}
- 更新用户信息DELETE /api/users/{id}
- 删除用户
7. 添加持久化层(可选)
如果你希望将数据持久化到数据库中,可以使用 Spring Data JPA:
- 在
pom.xml
文件中添加依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
- 修改
User.java
:
package com.example.demo.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// Getters and Setters
}
- 创建
UserRepository.java
:
package com.example.demo.repository;
import com.example.demo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
- 修改
UserController.java
使用UserRepository
:
package com.example.demo.controller;
import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping
public List<User> getAllUsers() {
return userRepository.findAll();
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userRepository.findById(id).orElse(null);
}
@PostMapping
public User createUser(@RequestBody User user) {
return userRepository.save(user);
}
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User updatedUser) {
User user = getUserById(id);
if (user != null) {
user.setName(updatedUser.getName());
user.setEmail(updatedUser.getEmail());
return userRepository.save(user);
}
return null;
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userRepository.deleteById(id);
}
}
8. 配置文件 (application.yml
)
在 src/main/resources
目录下找到或创建 application.yml
文件,并添加以下内容来配置 MySQL 数据库连接:
spring:
datasource:
url: jdbc:mysql://localhost:3306/your_database_name?useSSL=false&serverTimezone=UTC
username: your_username
password: your_password
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
database-platform: org.hibernate.dialect.MySQL8Dialect
server:
port: 8080
确保有Mysql驱动依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>