Spring Boot RESTful API开发教程
package com.example.demo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/users")
public class UserController {
private final UserRepository repository;
@Autowired
public UserController(UserRepository repository) {
this.repository = repository;
}
@GetMapping("/")
public List<User> getUsers() {
return repository.findAll();
}
@PostMapping("/")
public User createUser(@RequestBody User user) {
return repository.save(user);
}
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return repository.findById(id).orElseThrow(() -> new RuntimeException("User not found"));
}
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User userDetails) {
User user = repository.findById(id)
.orElseThrow(() -> new RuntimeException("User not found"));
user.setName(userDetails.getName());
user.setEmail(userDetails.getEmail());
return repository.save(user);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
repository.deleteById(id);
}
}