AOP가 필요한 상황

Untitled

문제

  1. 회원가입, 회원 조회에 시간을 측정하는 기능은 핵심 관심 사항이 아니다.
  2. 시간을 측정하는 로직은 공통 관심 사항이다.
  3. 시간을 측정하는 로직과 핵심 비즈니스의 로직이 섞여서 유지보수가 어렵다.
  4. 시간을 측정하는 로직을 별도의 공통 로직으로 만들기 매우 어렵다.
  5. 시간을 측정하는 로직을 변경할 때 모든 로직을 찾아가면서 변경해야 한다.

AOP 적용

Untitled

AOP: Aspect Oriented Programming

공통 관심 사항(cross-cutting concern) vs 핵심 관심 사항(core concern) 분리.

aop.TimeTraceAop

@Aspect  //AOP 사용.
@Component
public class TimeTraceAop {

    @Around("execution(* hello.hellospring..*(..))")    //해당 aop를 적용할 범위를 지정. hellospring 패키지 내의 모든 파일에 적용.
    public Object execute(ProceedingJoinPoint joinPoint) throws 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");
        }
    }
}

해결

Untitled

Untitled

AOP를 적용하면 스프링 실행 시 먼저 프록시 객체를 호출하여 AOP를 실행하고 joinPoint.proceed() 실행 시에 실제 컨트롤러, 서비스, 레포지토리가 동작한다.