Spring Boot/AOP

Spring Boot AOP 실습3 JoinPoint, @AfterReturning

최-코드 2024. 7. 30. 21:50

어드바이스의 매개변수엔 JoinPoint라는 클래스 타입의 변수를 가질 수 있다. 이 변수를 통해 타겟의 정보를 얻을 수 있다.

@Aspect
@Component
public class AopClass{
    @Before("execution(~~~)")
    public void aopMethod1(JoinPoint joinPoint){
        // 타겟의 시그니처 가져오기
        MethodSignature methodSig = (MethodSignature) theJoinPoint.getSignature();
        System.out.println("Method: " + methodSig);
        
        //타겟의 인수 가져오기
        Object[] args = theJoinPoint.getArgs();
        for (Object tempArg : args) {
            System.out.println(tempArg);
        }
    }
}

@AfterReturning :

  • 메소드가 성공적으로 실행된 후에 실행되는 어드바이스를 지정하는 JoinPoint 어노테이션이다.
  • 사전처리 하는 @Before와 달리 반환되는 값이나 데이터를 후처리할 때 쓰인다. 따라서 @AfterReturning 어노테이션 속성에 pointcut은 물론(이 때 속성명으로 pointcut 지정해줘야함), returning 속성을 추가하여 반환되는 값을 저장할 수 있다. 여기서 설정한 이름과 어드바이스에서 설정되는 매개변수의 이름이 같아야 한다.
@Aspect
@Component
public class AopClass{
    @AfterReturning(pointcut="execution(~~~)", returning="result")
    public void aopMethod1(JoinPoint joinPoint, Object result){
        System.out.println(result.toString);
    }
}
  • 추가적으로 타겟 메소드가 반환되기 전에 반환 값을 수정하거나, 추가하거나, 제거할 수 있다. 하지만 이 때 returning의 값이 래퍼런스를 사용하는 인스턴스만 가능하다.
...
    public void aopMethod1(JoinPoint joinPoint, UserEntity result){
        result.setUsername("aop test");
    }
...