Spring AOP 적용 방법
1. build.gradle 설정
//aop
implementation 'org.springframework.boot:spring-boot-starter-aop'
2. Application 클래스에 추가
@EnableAspectJAutoProxy
@EnableJpaAuditing
@SpringBootApplication
@EnableCaching
public class WonyShopApplication {
public static void main(String[] args) {
SpringApplication.run(WonyShopApplication.class, args);
}
}
@EnableAspectJAutoProxy
3. 실행시간 측정 Timer 어노테이션 정의
@Target({ElementType.METHOD,ElementType.ANNOTATION_TYPE} )
@Retention(RetentionPolicy.RUNTIME)
public @interface Timer {
}
4. 실행측정 AOP 클래스
package study.wonyshop.aop;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
@Slf4j
@Aspect
@Component
public class ExecutionTimer {
@Pointcut("@annotation(study.wonyshop.aop.Timer)")
private void timer(){}
@Pointcut("within(*..*Controller)")
private void cut(){}
@Around("timer()")
public Object AssumeExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Object proceed = joinPoint.proceed();
stopWatch.stop();
long totalTimeMillis = stopWatch.getTotalTimeMillis();
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String methodName = signature.getMethod().getName();
log.info("실행 메서드: {}, 실행시간 = {}ms", methodName, totalTimeMillis);
return proceed;
}
}
멋집니다! 어디서 많이 본듯한 느낌이 듭니다..ㅋㅋㅋㅋ