Spring & SpringBoot

💡 Spring Boot에서 @RestControllerAdvice는 어디까지 적용될까?

창따오 2025. 7. 25. 16:18
728x90

Spring Boot에서 예외 처리를 전역으로 적용할 때 사용하는 @RestControllerAdvice,
그런데 문득 이런 궁금증이 들었습니다.

❓ "@RestControllerAdvice에 basePackages를 명시하지 않으면 어디까지 적용될까?"

 

✅ 결론 먼저

@RestControllerAdvice에 basePackages, assignableTypes 등을 지정하지 않으면...

👉 해당 클래스는 @Controller 또는 @RestController가 붙은 모든 클래스에 전역 적용됩니다.

 


🔍 기본 동작 원리

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<String> handleIllegalArgument(IllegalArgumentException e) {
        return ResponseEntity.badRequest().body(e.getMessage());
    }
}

이처럼 선언하면:

  • @SpringBootApplication이 위치한 패키지를 기준으로 ComponentScan이 수행되고,
  • 해당 범위 내 모든 Controller에 대해 전역 예외 처리가 자동 적용됩니다.

즉, 기본 스코프는 애플리케이션 전체라고 보면 됩니다.


🧪 실습 예시

1. Global Advice

@RestControllerAdvice
public class GlobalAdvice {
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<?> handle(RuntimeException e) {
        return ResponseEntity.internalServerError().body("서버 오류 발생: " + e.getMessage());
    }
}

→ 모든 컨트롤러에서 RuntimeException이 발생하면 이 핸들러가 실행됩니다.

 

2. 특정 패키지만 적용하고 싶을 때

@RestControllerAdvice(basePackages = "com.example.auth")
public class AuthAdvice {
    @ExceptionHandler(AuthException.class)
    public ResponseEntity<?> handle(AuthException e) {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(e.getMessage());
    }
}

com.example.auth 하위 컨트롤러에서만 적용됩니다.

 


🚀 MSA 환경에서의 활용 전략

마이크로서비스 구조에선 서비스마다 모듈이 분리되기 때문에, 아래처럼 설정하면 유용합니다.

전략설명
서비스 전용 Advice basePackages 또는 assignableTypes로 각 서비스 전용 예외 핸들러를 분리
공통 라이브러리화 공통 예외 핸들러를 라이브러리로 분리 후 의존성 주입
Gateway에선 처리 X Gateway에서는 ControllerAdvice가 작동하지 않음. 대신 오류 메시지는 각 서비스에서 JSON 형태로 Response 내려줘야 함.
 

🧠 마무리

@RestControllerAdvice는 매우 강력한 예외 처리 도구입니다.
기본 설정만으로도 전체 컨트롤러에 일괄 적용되기 때문에,

  • 작은 프로젝트에서는 전역 핸들러 하나로도 충분하고,
  • MSA나 모듈 분리된 프로젝트에서는 basePackages를 이용해 범위를 나눠주는 것이 좋습니다.