Dowon Lee님의 Spring Boot를 이용한 RESTful Web Services 개발 강의를 학습한 내용입니다.
@Service
public class UserDaoService {
//...
}
- @Service : Service 용도의 Bean
@RestController
public class UserController {
private UserDaoService service;
public UserController(UserDaoService service){
this.service = service;
} //생성자를 통한 의존성 주입
//...
}
- 생성자를 통한 의존성 주입
@GetMapping("/users")
public List<User> retrieveAllUsers(){
return service.findAll();
}
@GetMapping("/users/{id}")
public User retrieveUser(@PathVariable int id){
return service.findOne(id);
}
- @GetMapping("/users/{id}") : user 상세조회 => ex) users/10 -> Controller에는 String으로 전달됨 -> int로 선언하면 String값이 자동으로 변환되어 매핑됨
@PostMapping("/users")
public ResponseEntity<User> createUser(@RequestBody User user){
User savedUser = service.save(user);
//URI 등록
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(savedUser.getId())
.toUri();
return ResponseEntity.created(location).build();
}
- @RequestBody : POST 메소드에서 사용, JSON 형식 데이터 추가
- 201 Created
@GetMapping("/users/{id}")
public User retrieveUser(@PathVariable int id){
User user = service.findOne(id);
if(user == null){
throw new UserNotFoundException(String.format("ID[%s] not found", id));
}
return user;
}
@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
- 404 Not Found
@RestControllerAdvice
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request){
ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(UserNotFoundException.class)
public final ResponseEntity<Object> handleUserNotFoundException(Exception ex, WebRequest request){
ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity(exceptionResponse, HttpStatus.NOT_FOUND);
}
}
- @RestControllerAdvice : @ResponseBody + @ControllerAdvice, @ControllerAdvice가 AOP를 적용해 컨트롤러 단에 적용
- ResponseEntity : 사용자 추가 시 반환시킨 값
- 404 Not Found : UserNotFound 일 때
- 500 Internal Server Error : 이외의 예외