AOP 적용

2023. 5. 3. 15:04카테고리 없음

우리가 원하는 곳에 할 수 있게 해주는 마법같은 그림.

시간 측정 AOP 등록

package com.example.demo.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
//이걸 쓰든지 Bean을 직접 주입하던지.

// @Bean
// public TimeTraceAop timeTraceAop() {
//         return new TiomTraceAop();
//    } SpringConfig에 추가하면됨

public class TimeTraceAop {

    @Around("execution(* com.example..*(..))") // 시간 측정 로직을 어디에다가 적용할 건지 정하는 역할.
    // @Around("execution(* com.example.service..*(..))") 만약 서비스에만 하고 싶다고 하면 뒤에 service를 넣어주면됨. 저장되어 있는
    // 파일의 위치를 넣는것이다.
    public Object excute(ProceedingJoinPoint joinPoint) throws Throwable { // 밑에 있는 시간 로직
        long start = System.currentTimeMillis();
        System.out.println("START: "  + joinPoint.toString());
        try {
            // Object result = joinPoint.proceed(): 밑에있는 joinPoint.proceed 와 한줄로 inline 시킨것.
            return joinPoint.proceed(); // 다음 메서드로 진행시켜주는 코드를 반환.
        } finally {
            long finish = System.currentTimeMillis();
            long timeMs = finish - start;
            System.out.println("END: " + joinPoint.toString()+" " + timeMs + "ms");
        }
    }
}

해결

  • 회원가입, 회원 조회등 핵심 관심사항과 시간을 측정하는 공통 관심 사항을 분리한다.
  • 시간을 측정하는 로직을 별도의 공통 로직으로 만들었다.
  • 핵심 관심 사항을 깔끔하게 유지할 수 있다.
  • 변경이 필요하면 이 로직만 변경하면 된다.
  • 원하는 적용 대상을 선택할 수 있다

실제 동작하는 방식

AOP 적용 전 의존 관계

helloController가 memberService를 의존하기 때문에 메서드 호출하면 Service께 그냥 나오지.

AOP적용 후 의존 관계

AOP가 있으면 Spring이 가짜Service Bean을 만들어 내고 가짜를 먼저 앞세워 실행시킨 뒤, 그 마지막에 joinPoint.proceed()가 있다면 실제 Service Bean을 호출해냄.

AOP적용 전과 후 전체의존관계

적용전
적용후