SpringBoot优雅开发REST API最佳实践
    		       		warning:
    		            这篇文章距离上次修改已过423天,其中的内容可能已经有所变动。
    		        
        		                
                
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
 
@RestController
@RequestMapping("/api/items")
public class ItemController {
 
    private final ItemService itemService;
 
    @Autowired
    public ItemController(ItemService itemService) {
        this.itemService = itemService;
    }
 
    @GetMapping
    public ResponseEntity<Page<Item>> listItems(@PageableDefault(size = 10, page = 0) Pageable pageable) {
        Page<Item> page = itemService.listItems(pageable);
        return ResponseEntity.ok(page);
    }
 
    @GetMapping("/{id}")
    public ResponseEntity<Item> getItem(@PathVariable("id") Long id) {
        Item item = itemService.getItemById(id);
        if (item == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(item);
    }
 
    @PostMapping
    public ResponseEntity<Item> createItem(@RequestBody Item item) {
        Item newItem = itemService.createItem(item);
        return ResponseEntity.ok(newItem);
    }
 
    @PutMapping("/{id}")
    public ResponseEntity<Item> updateItem(@PathVariable("id") Long id, @RequestBody Item item) {
        Item updatedItem = itemService.updateItem(id, item);
        if (updatedItem == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(updatedItem);
    }
 
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteItem(@PathVariable("id") Long id) {
        itemService.deleteItemById(id);
        return ResponseEntity.noContent().build();
    }
}这个代码实例展示了如何使用Spring Boot创建REST API控制器。它遵循了REST API设计的最佳实践,包括使用Pageable进行分页、使用ResponseEntity进行响应处理、使用@PathVariable和@RequestBody注解来处理路径变量和请求体中的数据,以及使用@RestController来标识控制器是以REST风格提供服务的。
评论已关闭