AOP(Aspect-Oriented Programming, 관점 지향 프로그래밍)은 핵심 비즈니스 로직과 부가적인 기능(공통 관심사, Cross-Cutting Concern)을 분리하여 코드의 모듈성을 향상시키는 프로그래밍 기법이다.
public class UserService {
public void createUser(String name) {
System.out.println("User created: " + name); // 핵심 기능
System.out.println("로그 기록: 사용자 생성"); // 공통 관심사 (AOP로 분리 가능)
}
}
→ AOP를 사용하면 로깅 코드를 핵심 비즈니스 로직에서 분리할 수 있다.
| 용어 | 설명 |
|---|---|
| Aspect | 부가 기능을 모듈화한 것 (e.g., 로깅, 트랜잭션 관리) |
| Join Point | AOP가 적용될 수 있는 지점 (메서드 실행, 객체 생성 등) |
| Advice | 실행할 부가 기능 (Before, After, Around 등) |
| Pointcut | Advice를 적용할 메서드 지정 (표현식 사용) |
| Weaving | Advice를 대상 객체에 적용하는 과정 (컴파일 시, 런타임 시) |
@Aspect와 @Around를 이용한 AOP 구현import org.aspectj.lang.annotation.*;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.stereotype.Component;
@Aspect // AOP 기능을 가진 클래스
@Component // 스프링 빈으로 등록
public class LoggingAspect {
@Around("execution(* com.example.service.*.*(..))") // 서비스 계층 모든 메서드에 적용
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
Object result = joinPoint.proceed(); // 실제 메서드 실행
long end = System.currentTimeMillis();
System.out.println(joinPoint.getSignature() + " 실행 시간: " + (end - start) + "ms");
return result;
}
}
@Aspect: AOP 클래스 선언@Around("execution(* 패키지.클래스.메서드(..))"): 대상 메서드 지정joinPoint.proceed(): 실제 비즈니스 로직 실행@Before와 @After를 이용한 AOP 적용@Aspect
@component
public class LoggingAspect {
@Before("execution(* com.example.service.UserService.*(..))")
public void beforeAdvice() {
System.out.println("메서드 실행 전 - 로그 기록");
}
@After("execution(* com.example.service.UserService.*(..))")
public void afterAdvice() {
System.out.println("메서드 실행 후 - 로그 기록");
}
}
@Before: 메서드 실행 전에 실행@After: 메서드 실행 후에 실행@Pointcut으로 중복 제거@Aspect
@Component
public class LoggingAspect {
@Pointcut("execution(* com.example.service.*.*(..))")
public void sericeMethods() {}
@Before("serviceMethods()")
public void beforeAdvice() {
System.out.println("메서드 실행 전 - 로그 기록");
}
@After("serviceMethods()")
public void afterAdvice() {
System.out.println("메서드 실행 후 - 로그 기록");
}
}
@Pointcut: 여러 Advice에서 재사용 가능@Aspect, @Before, @After, @Around 등을 사용하여 구현AOP를 활용하면 더 유지보수하기 쉬운 코드를 만들 수 있다.