Backend/SpringBoot

AOP (함수 실행 intercept)

Dean83 2024. 10. 30. 11:57

함수들이 실행 될 때마다 중간에 intercept 하여 여러가지 작업을 할 수 있다. 예를들어 실행 시간 측정이나, 인자값 검사, 로깅 작성등이 가능하다.

 

쉽게 생각하면 클라이언트에서 RESTAPI 통신을 할때  Request 혹은 Response를 처리하는 함수를 Intercept 하여 로깅을 작성하든지, header를 조작하든지 하는 작업과 같은 것이라고 보면 된다. 

 

  • @Aspect 어노테이션
    • 클래스에 붙이는 어노테이션으로, AOP 임을 명시한다.
  • @Around 어노테이션
    • 함수에 붙이는 어노테이션으로 다양한 문법이 있으나, 보통 적용대상 설정을 많이 사용한다.
      • @Around("execution(* 패키지경로..*(..))")
    • 함수는 Bean에 등록되야 하므로, @Configuration 을 이용해 등록해 준다. 
package com.example.test1.test1;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class aop {
    
    @Bean
    @Around("execution(* 패키지경로..*(..))")
    public Object InterceptTest(ProceedingJoinPoint point) throws Throwable
    {
        long st = System.currentTimeMillis();
        try {
        	//인터셉트 한 함수 계속 실행
            return point.proceed();
        } finally {
            long ed = System.currentTimeMillis();
            //인터셉트 항목 문자열로 출력
            System.err.println(point.toString() + " " + (ed - st));
        }
        

    }
}