Spring 기초 정리 - AOP

Zyoon·2025년 6월 12일

Spring 기초정리

목록 보기
14/18
post-thumbnail

📘AOP 의 사용이유와 사용법 정리


AOP란?

  • 어떤 메서드 실행 전이나 후에 공통적으로 반복되는 작업이 있다고 가정해보자.
  • 예를 들어 로깅, 트랜잭션 처리, 권한 체크, 실행 시간 측정 같은 기능.
  • 이러한 작업을 각 메서드에 매번 직접 코딩하면 유지보수도 어렵고 비효율적이다.
  • 이럴 때 사용하는 것이 바로 AOP이다.

AOP의 역할 (Advice 종류)

  1. @Before
    • 타겟 메서드 실행 실행됨
    • 주로 로그 시작, 파라미터 검증, 권한 체크 등에 사용
  2. @AfterReturning
    • 타겟 메서드가 정상적으로 리턴된 후 실행됨
    • 결과값 가공, 성공 로그 등
  3. @AfterThrowing
    • 타겟 메서드가 예외를 던졌을 때 실행됨
    • 예외 처리, 에러 로깅 등
  4. @After
    • 메서드 실행 성공/실패 상관없이 무조건 실행됨
    • 리소스 정리 등
  5. @Around
    • 메서드 실행 전후를 모두 감싸서 처리
    • 실행 시간 측정, 성능 로깅, 전체 흐름 제어 등

AOP 예시

요청 메서드 전후로 로그를 남기는 기능

  • logExecution() - 로그 전용 클래스
@Slf4j
public class AopLogger {

		private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

		public static void log(String methodName, String phase) {
        String timestamp = LocalDateTime.now().format(FORMATTER);
        log.info("[{}] {} - {}", timestamp, methodName, phase);
    }
}
  • Aspect 클래스 생성 - @Aspect, @Component
@Slf4j
@Aspect
@Component
public class LoggingAspect {

    @Around("execution(* org.example.expert.domain.auth.service.AuthService.signin(..))")
    public Object logSigninExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        String methodName = joinPoint.getSignature().toShortString();

        log.info("[AOP] {} - 메서드 실행 시작", methodName);

        long start = System.currentTimeMillis();
        try {
            Object result = joinPoint.proceed();  // 실제 signin 메서드 실행
            log.info("[AOP] {} - 메서드 정상 종료", methodName);
            return result;
        } catch (Throwable e) {
            log.error("[AOP] {} - 메서드 예외 발생: {}", methodName, e.getMessage());
            throw e;
        } finally {
            long end = System.currentTimeMillis();
            log.info("[AOP] {} - 실행 시간: {} ms", methodName, (end - start));
        }
    }
}

AOP 초기 설정

  • Spring Boot에서는 따로 설정할 필요 없음
  • AOP는 @Aspect@Component만 붙이면 자동 적용됨
  • 단, spring-boot-starter-aop 의존성 필요
// build.gradle
implementation 'org.springframework.boot:spring-boot-starter-aop'

AOP 와 Interceptor 비교

항목AOP (Aspect)Interceptor
적용 대상모든 메서드 (서비스, 레포 등 포함)스프링 MVC 요청 (컨트롤러 중심)
위치실제 메서드 실행 전후DispatcherServlet 앞뒤
주 사용 목적트랜잭션/성능로깅/공통 비즈니스 처리 등인증/권한/로깅/URI 처리 등
설정 방식@Aspect 선언 + 포인트컷 작성WebMvcConfigurer 통해 등록
의존성 필요spring-boot-starter-aop 필요없음
profile
기어 올라가는 백엔드 개발

0개의 댓글