본문 바로가기

springboot

[스프링 입문] 6. AOP

만약에 모든 method의 호출 시간을 측정하고 싶다고 했을 때,

호출 시간을 측정하는 것이 공통 관심 사항이 되고, 핵심 로직을 핵심 관심 사항이라고 한다.

 

호출 시간을 측정하는 것은 한 메소드 전체를 감싸야하기 때문에, 따로 method를 만들어서 사용하기도 힘들다.

그럴 때 AOP를 사용해서 원하는 곳에 공통 관심 사항(시간 측정)을 적용한다.

 

 

TimeTraceAop를 하나 만든다. 

@Component
@Aspect
public class TimeTraceAop {
}

AOP는 @Aspect라는 어노테이션이 필요하다.  

또한 스프링 빈으로 등록해줘야하기 때문에 SpringConfig에 설정을 추가하거나, @Component 어노테이션을 달아준다.

보통 AOP는 직접 등록해서 사용한다. 

@Component
@Aspect
public class TimeTraceAop {

    @Around("execution(* dare.springpractice..*(..))") // targeting springpractice 밑의 패키지에 모두 적용
    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");
        }

    }
}

@Around를 사용해서 어디에 적용할 지 targeting한다. 

다른 기능이 필요하다면 try 안에서 분기해서 진행할 수도 있다. 

 

테스트 해보면 AOP가 적용된 걸 확인할 수 있다. 

 

AOP를 적용하면 의존관계가 아래와 같이 변한다. 

AOP 적용 전
AOP 적용 후

 

 

 

 

강의에서 진행한 내용은 여기까지이다.

작성한 코드는 깃헙에 업로드했다. 

https://github.com/G-D4R3/spring-introduction.git