스프링 핵심 원리(고급편)

Ch11. 스프링 AOP(포인트컷) - 매개변수 전달

webmaster 2022. 4. 20. 15:36
728x90

포인트 컷 표현식을 사용해서 어드바이스에 매개변수를 전달할 수 있다. this, target, args,@target, @within, @annotation, @args

@Slf4j
@Import(ParameterTest.ParameterAspect.class)
@SpringBootTest
public class ParameterTest {

    @Autowired
    MemberService memberService;

    @Test
    public void success(){
        log.info("memberService Proxy={}", memberService.getClass());
        memberService.hello("helloA");
    }

    @Slf4j
    @Aspect
    static class ParameterAspect{
        @Pointcut("execution(* hello.aop.member..*.*(..))")
        private void allMember(){

        }

        @Around("allMember()")
        public Object logArg1(ProceedingJoinPoint joinPoint) throws Throwable {
            Object arg1 = joinPoint.getArgs()[0];
            log.info("[logArgs1]{}, arg={}", joinPoint.getSignature(), arg1);
            return joinPoint.proceed();
        }

        @Around("allMember() && args(arg, ..)")
        public Object logArg2(ProceedingJoinPoint joinPoint, Object arg) throws Throwable {//파라미터 받기 가능
            log.info("[logArgs2]{}, arg={}", joinPoint.getSignature(), arg);
            return joinPoint.proceed();
        }

        @Before("allMember() && args(arg, ..)")
        public void logArgs3(String arg){
            log.info("[logArgs3] arg={}", arg);
        }

        @Before("allMember() && this(obj)")
        public void thisArgs(JoinPoint joinPoint, MemberService obj){
            //프록시객체
            log.info("[this]{}, obj={}", joinPoint.getSignature(), obj.getClass());
        }


        @Before("allMember() && target(obj)")
        public void targetArgs(JoinPoint joinPoint, MemberService obj){
            log.info("[target]{}, obj={}", joinPoint.getSignature(), obj.getClass());
        }

        @Before("allMember() && @target(annotation)")
        public void atTarget(JoinPoint joinPoint, ClassAop annotation){
            log.info("[@target]{}, obj={}", joinPoint.getSignature(), annotation);
        }

        @Before("allMember() && @within(annotation)")
        public void atWithin(JoinPoint joinPoint, ClassAop annotation){
            log.info("[@within]{}, obj={}", joinPoint.getSignature(), annotation);
        }

        @Before("allMember() && @annotation(annotation)")
        public void atAnnotation(JoinPoint joinPoint, MethodAop annotation){
            log.info("[@annotation]{}, annotationValue={}", joinPoint.getSignature(), annotation.value());
        }
    }

}
  • logArgs1 : joinPoint.getArgs()[0]와 같이 매개변수를 전달받는다.
  • logArgs2 : args(arg,..) 와 같이 매개변수를 전달받는다.
  • logArgs3 : @Before 를 사용한 축약 버전이다. 추가로 타입을 String으로 제한했다.
  • this : 프록시 객체를 전달받는다.
  • target : 실제 대상 객체를 전달받는다.
  • @target , @within : 타입의 애노테이션을 전달 받는다.
  • @annotation : 메서드의 애노테이션을 전달 받는다. 여기서는 annotation.value()로 해당 애노테이션의 값을 출력하는 모습을 확인할 수 있다.
728x90