개발/Spring

Spring에서 인터셉터(HandlerInterceptor) 와 AOP(Aspect Oriented Programming) 차이

피터JK 2025. 10. 3. 11:20
728x90

Spring에서 인터셉터(HandlerInterceptor)AOP(Aspect Oriented Programming) 는 비슷하게 보이지만, 적용 범위와 동작 방식이 달라요. 정리해드릴게요.


1. 공통점

  • 둘 다 횡단 관심사(Cross-cutting concern) 를 처리할 때 사용됨.
    (ex: 로깅, 인증/인가, 성능 측정, 트랜잭션 처리 등)
  • 특정 로직을 반복해서 작성하지 않고 공통 모듈로 관리할 수 있음.

2. 차이점

구분 인터셉터 (HandlerInterceptor) AOP (Aspect Oriented Programming)

적용 대상 Spring MVC의 컨트롤러 요청/응답 흐름
(DispatcherServlet → Controller)
Spring Bean(메서드 실행) 전/후/예외 처리
동작 레벨 웹 계층 (HTTP 요청 단위) 서비스/비즈니스 로직 계층 (메서드 단위)
위치 DispatcherServlet에서 컨트롤러 실행 전후 스프링 IoC 컨테이너에서 관리되는 Bean 메서드 실행 시
주요 용도 인증/인가, 요청/응답 로깅, Locale 처리, 세션 체크 등 트랜잭션 관리, 로깅, 성능 모니터링, 공통 비즈니스 로직
구현 방식 HandlerInterceptor 인터페이스 구현 (preHandle, postHandle, afterCompletion) AspectJ, Spring AOP → @Aspect, @Around, @Before, @After 등
적용 범위 주로 컨트롤러 레벨 모든 Spring Bean (특히 Service, Repository 계층)
비유 “HTTP 요청의 문지기” “메서드 실행에 끼어드는 조력자”

3. 흐름

  • 인터셉터 흐름
Client → DispatcherServlet 
   → [인터셉터 preHandle] 
       → Controller 
   → [인터셉터 postHandle] 
   → ViewResolver 
   → [인터셉터 afterCompletion]
  • AOP 흐름
Service.method() 실행 시  
   → [Before Advice]  
       → 실제 메서드 실행  
   → [After / Around Advice]  
   → [예외 발생 시 AfterThrowing Advice]

4. 간단한 예시

인터셉터 예시

public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (request.getSession().getAttribute("user") == null) {
            response.sendRedirect("/login");
            return false;
        }
        return true;
    }
}

AOP 예시

@Aspect
@Component
public class LoggingAspect {

    @Around("execution(* com.example.service.*.*(..))")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();
        System.out.println(joinPoint.getSignature() + " 실행 시간: " + (end - start) + "ms");
        return result;
    }
}

정리

  • 인터셉터 → Spring MVC 요청/응답 과정에 개입 (웹 계층)
  • AOP → 메서드 실행에 개입 (비즈니스 계층)

 

728x90