본문 바로가기
spring

AOP

by 김선지 2024. 5. 19.

AOP가 필요한 상황

 

Aspect Oriented Programming

공통 관심 사항, 해당 로직을 필요한 부분에 적용 (모든 함수에 대해 걸리는 시간 측정) 

메소드 호출시 인터셉트해서 함수를 실행

ex) 시간을 측정하는 로직을 별도의 공통 로직으로 만든다.

 

적용 전 의존관계

controller -> service

 

적용 후 의존관계

controller -> 프록시(가짜)service --- joinPoint.proceed() ----> 실제 service

aop.TimeTraceAop

@Aspect
@Component // or config에서 bean으로 등록 <- 선호
public class TimeTraceAop {

	@Around("execution(* hello.hellospring..*(..))") // package명, 모든 메서드에서 적용됨.
    // * hello.hellospring.service..*(..)으로 작성하면 service단 안에 있는 것들만 적용.
    
	public Object excute(ProceedingJoinPoint joinPoint) throw Throwable{
    	long start = System.currentTimeMillis();
        System.out.println("start: " + joinPoint.toString());
        try {
         return joinPoint.proceed();
        } finally {
        	long finish = System.currentTimeMillis();
            long timeMs = finish - start;
            System.out.println("END: " + joinPoint.toString() + " " + timeMs + "ms");
        }
       
    }
}