티스토리 뷰

Spring

[Spring] AOP @target, @within

hyuuny 2022. 6. 6. 17:54

@target vs @within

@target은 인스턴스의 모든 메서드를 조인 포인트로 적용하고, @within은 해당 타입 내에 있는 메서드만 조인 포인트로 적용한다. 이를 풀어서 이야기하면, @target은 부모 클래스의 메서드까지 어드바이스를 다 적용하고, @within은 자기 자신의 클래스에 정의된 메서드에만 어드바이스를 적용한다는 것이다.



Test code

@Slf4j
@Import({AtTargetAtWithinTest.Config.class})
@SpringBootTest
public class AtTargetAtWithinTest {

  @Autowired
  Child child;

  @Test
  void success() {
    log.info("child Proxy={}", child.getClass());
    child.childMethod(); //부모, 자식 모두 있는 메서드
    child.parentMethod(); //부모 클래스만 있는 메서드
  }

  static class Config {

    @Bean
    public Parent parent() {
      return new Parent();
    }

    @Bean
    public Child child() {
      return new Child();
    }

    @Bean
    public AtTargetAtWithinAspect atTargetAtWithinAspect() {
      return new AtTargetAtWithinAspect();
    }
  }

  static class Parent {

    public void parentMethod() {} //부모에만 있는 메서드

    @ClassAop
    static class Child extends Parent {

      public void childMethod() {}

    }

    @Slf4j
    @Aspect
    static class AtTargetAtWithinAspect {

      //@target: 인스턴스 기준으로 모든 메서드의 조인 포인트를 선정, 부모 타입의 메서드도 적용
      @Around("execution(* com.hyuuny.advanced.aop..*(..)) && @target(com.hyuuny.advanced.member.annotation.ClassAop) ")
      public Object atTarget(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("[@target] {}", joinPoint.getSignature());
        return joinPoint.proceed();
      }

      //@within: 선택된 클래스 내부에 있는 메서드만 조인 포인트로 선정, 부모 타입의 메서드는 적용되지 않음
      @Around("execution(* com.hyuuny.advanced.aop..*(..)) && @within(com.hyuuny.advanced.member.annotation.ClassAop) ")
      public Object atWithin(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("[@within] {}", joinPoint.getSignature());
        return joinPoint.proceed();
      }
    }

  }

}

success 결과

parentMethod()Parent클래스에만 정의되어 있고, Child클래스에 정의되어 있지 않기 때문에 @within에서 AOP 적용 대상이 되지 않는다.
실행결과를 보면 child.parentMethod()를 호출 했을 때 [@within]이 호출되지 않은 것을 확인할 수 있다.



Reference
김영한. 스프링 핵심 원리 - 고급편. 인프런.

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%ED%95%B5%EC%8B%AC-%EC%9B%90%EB%A6%AC-%EA%B3%A0%EA%B8%89%ED%8E%B8#

'Spring' 카테고리의 다른 글

[Spring] 스프링 트라이앵글 - IoC/DI, AOP, PSA  (0) 2022.08.26
[Spring Security] JWT (Json Web Token)  (0) 2022.07.21
[Spring] AOP Pointcut execution  (0) 2022.05.31
[Spring] Advice 종류  (0) 2022.05.29
[Spring] AOP 용어  (0) 2022.05.25
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함