Spring Framework 에서 전역적으로 예외를 처리하거나, 특정 컨트롤러 클래스에 대한 공통 기능을 제공할 때 사용하는 어노테이션.
@ControllerAdvice를 사용하면 여러 컨트롤러에서 공통적으로 사용될 로직을 한 곳에 모아 관리할 수 있음
@ExceptionHandler)@ModelAttribute)@InitBinder)예외 처리(@ExceptionHandler 와 함께 사용)
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
public ResponseEntity<Object> handleException(Exception ex) {
return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
모든 컨트롤러에서 발생하는 Exception 을 전역적으로 처리함. 예외가 발생하면, HTTP 상태 코드 500과 함께 에러메세지를 반환
전역 데이터 바인딩(@ModelAttribute)
@ControllerAdvice
public class GlobalModelAttribute {
@ModelAttribute
public void addAttributes(Medel model) {
model.addAttribute("globalAttribute", "This is a global attribute");
}
}
모든 컨트롤러의 뷰에 "globalAttribute" 라는 이름의 속성을 추가
전역적인 데이터 포맷팅(@InitBinder)
@ControllerAdvice
public class GlobalBindingConfig {
@InitBinder
public void initBinder(WebDataBinder binder) {
// 특정 필드 이름에 대해 특정 타입으로 변환하는 커스텀 에디터 설정
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
}
}
모든 컨트롤러에서 날짜 형식을 "yyyy-MM-dd" 로 처리하도록 설정
@ControllerAdvice 는 @ExceptionHandler 와 결합하여 어플리케이션 전반에서 예외를 일관되게 처리할 수 있는 강력한 도구임
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = NullPointerException.class)
public ResponseEntity<Object> handleNullPointerException(NullPointerException ex) {
return new ResponseEntity<>("Null value encountered: " + ex.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(value = IllegalArgumentException.class)
public ResponseEntity<Object> handleIllegalArgumentException(IllegalArgumentException ex) {
return new ResponseEntity<>("Illegal argument: " + ex.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(value = Exception.class)
public ResponseEntity<Object> handleGenericException(Exception ex) {
return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
이러한 예외 처리를 통해 어플리케이션의 예외 관리를 중앙집중식으로 할 수 있으며, 일관된 오류 응답을 제공할 수 있음