AOP를 설정해보자
Advice + PointCut = Aspect
어드바이스(Advice)
애스펙트(Aspect)
어드바이저(Advisor)
<!--3. AOP -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
package com.codesign.base.common.aop;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Slf4j
@Aspect
@Component
public class LoggerAspect {
private final String EXECUTION = "execution(* com.codesign.base..service..*(..))";
@Around(EXECUTION)
public Object printLog(ProceedingJoinPoint joinPoint) throws Throwable {
log.info("@Around start");
String name = joinPoint.getSignature().getDeclaringTypeName();
log.info("@Around name : {}", name); // >>> com.codesign.base.member.service.impl.MemberServiceImpl
long beforeTime = System.currentTimeMillis();
Object proceed = joinPoint.proceed();
long afterTime = System.currentTimeMillis();
long secDiffTime = (afterTime - beforeTime);
log.info("시간차이(m) : {}", secDiffTime);
log.info("@Around end");
return proceed;
}
@Before(EXECUTION)
public void printBeforeLog() throws Throwable {
log.info("@Before <<<<<<<<<<<<<<<<<<<<<<<<<<<< ");
}
@After(EXECUTION)
public void printAfterLog() throws Throwable {
log.info("@After >>>>>>>>>>>>>>>>>>>>>>>>>>>> ");
}
@AfterReturning(EXECUTION)
public void printAfterReturningLog() throws Throwable {
log.info("@AfterReturning >>>>>>>>>>>>>>>>>>>>>>>>>>>> ");
}
@AfterThrowing(EXECUTION)
public void printAfterThrowingLog() throws Throwable {
log.info("@AfterThrowing >>>>>>>>>>>>>>>>>>>>>>>>>>>> ");
}
}
@Aspect
Aspect 모듈화 선언
AOP 표현식 - execuation()
* com.codesign.base..service..*(..)
com.codesign.base..
: com.codesign.base
패키지 및 하위 패키지service..
: service
서비스 패키지 하위*(..)
0개 이상의 인자를 받는 모든 메서드com.codesign.base 패키지 아래, service패키지 안에 있는 0개 이상의 인자를 받는 모든 메서드
속성 | 설명 |
---|---|
@Around | @Around 어노테이션에서만 ProceedingJoinPoint 를 인자로 받을 수 있다. |
joinPoint.proceed();가 메서드를 실행하는 부분이고, 이 로직 실행전후 로직을 추가할 수 있다. | |
void로 만들면 메서드 실행결과가 리턴되지 않아 실행결과를 return 해줘야한다. | |
@Before | 메서드 실행전 |
@After | 메서드 실행후 |
@AfterReturning | 메서드 실행 성공 |
@AfterThrowing | 메서드 실행 실패 |
참고
https://engkimbs.tistory.com/746
https://shlee0882.tistory.com/206