정의

Spring AOP는 비즈니스 로직과 공통 기능을 분리해 코드 중복을 줄이는 방식이다.

로깅, 보안, 트랜잭션처럼 여러 곳에서 반복되는 작업을 한 곳에 모아 관리할 때 유용하다.

📌 @Aspect

  • AOP의 핵심이 되는 애너테이션이다.
  • Advice와 Pointcut을 담는 클래스를 표시할 때 사용한다.
  • 일반적으로 @Component와 함께 등록한다.

예시

@Component
@Aspect
public class LoggingAspect {
    @Before("execution(* com.example..*.*(..))")
    public void logBefore(JoinPoint joinPoint){
        System.out.println("Before method: " + joinPoint.getSignature().getName());
    }
}

📌 @Before

  • 대상 메서드가 실행되기 전에 호출된다.
  • 사전 검사, 로그 기록, 권한 확인 등에 사용한다.

예시

@Before("execution(* com.example.controller..*.*(..))")
public void beforeAdvice(JoinPoint joinPoint){
    System.out.println("메서드 실행 전 호출됨: " + joinPoint.getSignature().getName());
}

📌 @After

  • 대상 메서드가 끝난 뒤 호출된다.
  • 예외 발생 여부와 관계없이 항상 실행된다.

예시

@After("execution(* com.example.controller..*.*(..))")
public void afterAdvice(JoinPoint joinPoint){
    System.out.println("메서드 실행 후 항상 호출됨: " + joinPoint.getSignature().getName());
}

📌 @AfterReturning

  • 대상 메서드가 정상적으로 종료된 뒤 호출된다.
  • 예외가 발생하면 실행되지 않는다.

예시

@AfterReturning("execution(* com.example.controller..*.*(..))")
public void afterReturningAdvice(JoinPoint joinPoint){
    System.out.println("정상 실행 후 호출됨: " + joinPoint.getSignature().getName());
}

📌 @AfterThrowing

  • 대상 메서드 실행 중 예외가 발생했을 때 호출된다.
  • 예외 로깅이나 에러 추적에 유용하다.

예시

@AfterThrowing("execution(* com.example.controller..*.*(..))")
public void afterThrowingAdvice(JoinPoint joinPoint){
    System.out.println("예외 발생 후 호출됨: " + joinPoint.getSignature().getName());
}

📌 @Around

  • 대상 메서드의 전후를 모두 제어할 수 있는 가장 강력한 애너테이션이다.
  • 메서드 실행을 직접 제어하며, proceed()로 실제 호출을 수행한다.

예시

@Around("execution(* com.example.controller..*.*(..))")
public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable{
    System.out.println("메서드 실행 전 호출됨");
    Object result = joinPoint.proceed();
    System.out.println("메서드 실행 후 호출됨");
    return result;
}

ProceedingJoinPoint 주요 메서드

메서드명 설명
getArgs() 메서드 인수 반환
getThis() 프록시 객체 반환
getTarget() 대상 객체 반환
proceed() 대상 메서드 직접 호출

🔄 애너테이션 비교

Annotation 실행 시점 메서드 호출
@Before 메서드 실행 전 자동
@After 메서드 실행 후 자동
@AfterReturning 정상 실행 후 자동
@AfterThrowing 예외 발생 시 자동
@Around 메서드 실행 전후 수동 (proceed())

🧰 설정 및 의존성

implementation 'org.springframework.boot:spring-boot-starter-aop'
implementation 'org.aspectj:aspectjrt'
implementation 'org.aspectj:aspectjweaver'

AOP 활성화 예시

@Configuration
@EnableAspectJAutoProxy
public class AopConfig {}

📌 장점과 단점

장점

  • 중복 코드 최소화
  • 로직 모듈화와 유지보수 용이
  • 횡단 관심사의 분리

단점

  • 실행 흐름이 복잡해질 수 있다
  • 과도하게 사용하면 추적이 어려워진다

📌 정리

  • AOP 애너테이션은 공통 로직을 분리할 때 유용하다.
  • @Aspect를 중심으로 @Before, @After, @Around 등을 조합한다.
  • 실행 전후를 세밀하게 제어하려면 @Around를 사용한다.

연결문서

댓글남기기