@ControllerAdvice는 Spring Framework에서 제공하는 어노테이션으로, 전역적으로 모든 컨트롤러에서 공통적인 동작을 정의할수 있도록 도와준다. 주로 예외 처리, 데이터 바인딩, 또는 모델 개게를 컨트롤러 메서드에 추가하는 데 사용된다.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGlobalException(Exception ex) {
return new ResponseEntity<>("Something went wrong: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleResourceNotFound(ResourceNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
}
상황:
@ControllerAdvice
public class GlobalModelAttribute {
@ModelAttribute("appName")
public String addGlobalAttributes() {
return "My Application";
}
}
상황:
@ControllerAdvice
public class JsonExceptionHandler {
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<String> handleInvalidJson(HttpMessageNotReadableException ex) {
return new ResponseEntity<>("Invalid JSON format: " + ex.getMessage(), HttpStatus.BAD_REQUEST);
}
}
상황:
@ControllerAdvice는 모든 컨트롤러에 적용되는 공통 로직을 정의할 때 유용하다.
이를 사용하면 코드의 중복을 줄이고, 유지보수를 용이하게 할 수 있다.
전역 예외 처리와 공통 데이터 추가가 가장 일반적인 사용 사례이다.