AOP

AOP(Aspect-Oriented Programming)는 공통 관심 사항(Cross-Cutting Concerns)을 모듈화하여 관리한다.

회원가입, 회원 조회에 시간을 측정하는 기능은 핵심 관심 사항(Core Concerns)가 아니고, 시간을 측정하는 로직은 공통 관심 사항이다. 하지만 각 기능에 시간을 측정하는 기능을 넣을 경우 비즈니스 로직이 섞여 유지보수가 어렵고, 시간을 측정하는 기능에 수정이 발생할 때 모든 부분을 수정해야해서 불편하다.

package hello.hello_spring.aop;

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

@Component
@Aspect
public class TimeTraceAop {
    @Around("execution(* hello.hello_spring..*(..))")
    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");
        }
    }
}

TimeTraceAop를 작성한다. @Aspect 어노테이션으로 AOP임을 나타내고, @Around 어노테이션으로 적용될 클래스를 명시한다. 스프링 빈에 올리기 위해 @Component 어노테이션을 사용한다. 이렇게 핵심 관심 사항과 공통 관심 사항을 분리할 수 있다.

AOP 적용 전에는 memberController가 memberService를 호출했다면, AOP 적용 후에는 memberController가 프록시 memberService(복제 된)를 호출하고, 프록시 memberService가 joinPoint.proceed() 메소드를 통해 실제 memberService를 호출하게 된다.


AOP를 마지막으로 스프링 입문 강의가 끝났다. 이번에 한 AOP도 그렇고 자세하게 공부할 것들이 많다...

'스터디 > Spring' 카테고리의 다른 글

Spring 스터디2 - 2  (0) 2025.03.30
Spring 스터디2 - 1  (0) 2025.03.23
Spring 스터디 - 6  (0) 2025.02.18
Spring 스터디 - 5  (0) 2025.02.17
Spring 스터디 - 4  (0) 2025.02.16

+ Recent posts