Spring Boot 3.x Rest API最佳实践之API设计
package com.example.demo.controller;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/v1/users")
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping
public ResponseEntity<List<User>> getAllUsers() {
return ResponseEntity.ok(userService.findAll());
}
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable("id") Long id) {
return ResponseEntity.ok(userService.findById(id));
}
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
return ResponseEntity.ok(userService.save(user));
}
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable("id") Long id, @RequestBody User user) {
return ResponseEntity.ok(userService.update(id, user));
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable("id") Long id) {
userService.deleteById(id);
return ResponseEntity.noContent().build();
}
}
这个代码实例展示了如何在Spring Boot 3.x中设计和实现一个简单的REST API控制器。它遵循了最佳实践,包括使用@RestController
注解来简化控制器的定义,使用ResponseEntity
来包装响应,并通过@RequestMapping
来定义路由。同时,它也展示了基本的CRUD操作,并通过userService
来与具体的业务逻辑实现进行交互。
评论已关闭