AOP - @Around 어노테이션

sarah·2023년 3월 29일
0

Around 어노테이션을 검색해봤을 때, 단순히 개념적인 설명만 있고
어떤 케이스에 사용하는지 예시가 다양하지 않아 직접 정리해 보았다.

개념

@Around 는 ‘핵심관심사’의 실패여부와 상관없이 전 후로 실행되록 하는 Advice로,
아래와 같이 메서드를 생성할 때,
return 값은 Object 이고, 인자는 ProceedingJoinPoint 이다.

@Around("포인트컷")
public Object before(ProceedingJoinPoint proceedingJoinPoint) {
	// 핵심관심사 실행 전 로직
	Object obj = proceedingJoinPoint.proceed();
    // 핵심관심사 실행 후 로직
}
  • Object => 해당 관심사가 실행되고 난 결과값
  • ProceedingJoinPoint => @Before, @After 어노테이션의 인자값 JoinPoint 인터페이스를 상속한 인터페이스로, proceed() 라는 메서드가 추가되는데, 이는 핵심관심사의 실행을 뜻하고, 결과값으로 위에서 설명한 Object를 결과값으로 받는다.

사용법

그래서 @Around 어노테이션을 이점을 살려서 사용하는 경우, 크게 두가지가 존재한다.
1. request와 response를 로깅할 수 있다.

@Around("포인트컷")
public Object before(ProceedingJoinPoint proceedingJoinPoint) {
	HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
    
    // request에서 필요한 데이터 가공해서 로그 남기는 로직
    
	Object obj = proceedingJoinPoint.proceed();
    
    
    // 핵심관심사의 결과값인 obj를 로그로 남기기
}
  1. proceed 메서드에 인자값을 Object[] 로 넣어주는 경우, 해당 인자값을 핵심관심사에게 넘겨준다.
    이를 잘 활용하면, 본래 인자값을 핵심관심사로 넘기기 전에 가공해서 넣어줄 수 있다.
@Around("포인트컷")
public Object before(ProceedingJoinPoint proceedingJoinPoint) {
	Object[] args = proceedindJoinPoint.getArgs();
    
    // args 가공 로직
    
	Object obj = proceedingJoinPoint.proceed(args);

}

0개의 댓글