
📘AOP 의 사용이유와 사용법 정리
@Before@AfterReturning@AfterThrowing@After@Around요청 메서드 전후로 로그를 남기는 기능
logExecution() - 로그 전용 클래스@Slf4j
public class AopLogger {
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public static void log(String methodName, String phase) {
String timestamp = LocalDateTime.now().format(FORMATTER);
log.info("[{}] {} - {}", timestamp, methodName, phase);
}
}
@Aspect, @Component@Slf4j
@Aspect
@Component
public class LoggingAspect {
@Around("execution(* org.example.expert.domain.auth.service.AuthService.signin(..))")
public Object logSigninExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
String methodName = joinPoint.getSignature().toShortString();
log.info("[AOP] {} - 메서드 실행 시작", methodName);
long start = System.currentTimeMillis();
try {
Object result = joinPoint.proceed(); // 실제 signin 메서드 실행
log.info("[AOP] {} - 메서드 정상 종료", methodName);
return result;
} catch (Throwable e) {
log.error("[AOP] {} - 메서드 예외 발생: {}", methodName, e.getMessage());
throw e;
} finally {
long end = System.currentTimeMillis();
log.info("[AOP] {} - 실행 시간: {} ms", methodName, (end - start));
}
}
}
@Aspect와 @Component만 붙이면 자동 적용됨spring-boot-starter-aop 의존성 필요// build.gradle
implementation 'org.springframework.boot:spring-boot-starter-aop'
| 항목 | AOP (Aspect) | Interceptor |
|---|---|---|
| 적용 대상 | 모든 메서드 (서비스, 레포 등 포함) | 스프링 MVC 요청 (컨트롤러 중심) |
| 위치 | 실제 메서드 실행 전후 | DispatcherServlet 앞뒤 |
| 주 사용 목적 | 트랜잭션/성능로깅/공통 비즈니스 처리 등 | 인증/권한/로깅/URI 처리 등 |
| 설정 방식 | @Aspect 선언 + 포인트컷 작성 | WebMvcConfigurer 통해 등록 |
| 의존성 필요 | spring-boot-starter-aop 필요 | 없음 |