SPRING

[SPRING] 인터셉터 AOP

도원좀비 2025. 4. 15. 21:19

1️⃣ 스프링 인터셉터란?

HandlerInterceptor 인터페이스를 구현하여,

DispatcherServlet → Controller로 가는 요청 사이에서 동작하는 필터 같은 존재입니다.

 

🗺️ 인터셉터 동작 흐름

클라이언트 → 디스패처서블릿
   ↓
 preHandle()
   ↓
 컨트롤러 실행
   ↓
 postHandle()
   ↓
 뷰 렌더링
   ↓
 afterCompletion()

 

🛠️ 사용 예시

public class LoggingInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.out.println("요청 URI: " + request.getRequestURI());
        return true; // false면 컨트롤러로 요청이 가지 않음
    }
}

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoggingInterceptor())
                .addPathPatterns("/api/**")
                .excludePathPatterns("/login", "/signup");
    }
}

2️⃣ AOP(Aspect-Oriented Programming)란?

AOP는 핵심 비즈니스 로직과 부가 로직을 분리하는 프로그래밍 패러다임입니다.
스프링에서는 @Aspect를 사용하여 메서드 실행 전/후 또는 예외 발생 시에 동작하는 Advice를 정의합니다.

🗺️ 동작 시점

  • @Before: 메서드 실행 전
  • @AfterReturning: 메서드 성공 후
  • @AfterThrowing: 예외 발생 시
  • @After: 성공/예외와 관계없이 항상 실행
  • @Around: 전/후 모두 제어 가능 (가장 강력)

 

🛠️ 사용 예시

@Aspect
@Component
public class LoggingAspect {

    @Around("execution(* com.example.service..*(..))")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();

        System.out.println("[AOP] " + joinPoint.getSignature() + " 실행 시간: " + (end - start) + "ms");
        return result;
    }
}

3️⃣ 인터셉터 vs AOP 비교

항목 인터셉터 AOP
적용 대상 컨트롤러 요청 전/후 빈 메서드 실행 전/후
대표 용도 인증, 권한 체크, 로깅 트랜잭션, 로깅, 공통 예외 처리
적용 범위 HTTP 요청 흐름 메서드 실행 단위 (더 세밀함)
설정 방식 WebMvcConfigurer로 등록 @Aspect, @Component, 포인트컷 설정
파라미터 접근 HttpServletRequest, HttpServletResponse JoinPoint, ProceedingJoinPoint

 

🎯 사용 상황

상황 추천 방식
인증/권한 검사 등 요청 URL 단위로 처리 인터셉터
서비스 메서드에서 로깅, 트랜잭션, 시간 측정 AOP
파라미터나 반환값을 조작하고 싶을 때 AOP (@Around)
요청 흐름을 제어하거나 응답을 조작할 때 인터셉터