BE/Spring & Spring Boot

[Spring Boot] @ControllerAdvice

baek-dev 2025. 1. 9. 20:20

Spring MVC에서 사용되는 어노테이션. 전역 예외 처리, 전역 데이터 바인딩, 전역 모델 처리와 관련 있다

컨트롤러 전역에서 특정 동작을 적용할 수 있도록 도와준다

 

관련된 어노테이션

1. @ExceptionHandler

  • 특정 예외(Exception) 발생 시 해당 예외를 처리하는 메서드에 사용된다
  • @ControllerAdvice와 함께 사용하면 모든 컨트롤러에서 발생한 특정 예외를 처리할 수 있다
  • 속성
    • value : 처리할 예외 타입을 지정
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity<String> handleNullPointerException(NullPointerException ex) {
        return new ResponseEntity<>("NullPointerException occurred: " + ex.getMessage(), HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception ex) {
        return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

 

관련 기능 : @RestControllerAdvice 를 사용하면 JSON형식으로 예외를 반환

2. @ModelAttibute

  • 모든 컨트롤러에서 공통으로 사용하는 모델 데이터를 정의할 때 사용된다
  • @ControllerAdvice 와 함께 사용하면 전역 모델 데이터를 설정할 수 있다
@ControllerAdvice
public class GlobalModelAttributeAdvice {

    @ModelAttribute
    public void addCommonAttributes(Model model) {
        model.addAttribute("appName", "My Spring Boot Application");
    }
}

 

결과 : 모든 컨트롤러에서 appName이라는 공통 속성을 사용할 수 있다

3. @InitBinder

  • 특정 컨트롤러에서 데이터 바인딩 또는 타입 변환을 설정할 때 사용된다
  • @ControllerAdvice 와 함께 사용하면 모든 컨트롤러에 대해 데이터 바인딩 설정을 전역적으로 적용할 수 있다
@ControllerAdvice
public class GlobalInitBinder {

    @InitBinder
    public void customizeBinding(WebDataBinder binder) {
        // 특정 필드에 대해 바인딩 제외
        binder.setDisallowedFields("password");
    }
}

 

결과 : 모든 컨트롤러에서 요청 데이터 중 password 필드가 무시된다


@ControllerAdvice vs @RestControllerAdvice

1. @ControllerAdvice

  • HTML 응답을 처리하는 컨트롤러 전역에서 사용
  • JSP, Thymeleaf와 같은 뷰 템플릿 엔진을 사용하는 경우에 적합

2. @RestControllerAdvice

  • JSON, XML데이터를 반환하는 REST API에서 사용
  • @ControllerAdvice + @ResponseBody 가 결합된 형태
@RestControllerAdvice
public class GlobalRestExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception ex) {
        return new ResponseEntity<>("Error: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

정리

  • @ControllerAdvice는 Spring MVC 애플리케이션에서 전역적인 예외 처리, 데이터 바인딩, 모델 처리에 사용된다
  • 이와 관련된 주요 애너테이션 :
    1. @ExceptionHandler : 특정 예외를 처리
    2. @ModelAttribute : 공통 데이터를 모든 컨트롤러에 추가
    3. @InitBinder : 데이터 바인딩이나 요청 데이터 처리 방식을 커스터마이징
  • REST API에서는 @RestControllerAdvice를 사용하면 JSON 응답 처리가 용이하다

 

 

 

 

출처 : ChatGPT

'BE > Spring & Spring Boot' 카테고리의 다른 글

[Spring Boot] List<Sort.Order>와 Sort.Order.desc()  (0) 2025.01.17
[Spring Boot, JPA] EntityManager  (1) 2025.01.16
[Spring Boot] PSA  (0) 2025.01.05
[Spring Boot] AOP  (0) 2025.01.05
[Spring Boot] DTO  (0) 2025.01.04