Spring Advanced

AOP (Part. 3) - 포인트컷

cwchoiit 2024. 1. 2. 15:20
728x90
반응형
SMALL
728x90
SMALL

포인트컷 지시자에 대해서 자세히 알아보자. 에스팩트J는 포인트컷을 편리하게 표현하기 위한 특별한 표현식을 제공한다. 예를 들면 이렇다.

@Pointcut("execution(* hello.aop.order..*(..))")

 

포인트컷 표현식은 'execution'과 같은 포인트컷 지시자(Pointcut Designator)로 시작한다. 줄여서 PCD라고도 한다.

 

포인트컷 지시자 종류

포인트컷 지시자의 종류는 다음과 같다.

  • execution: 메서드 실행 조인 포인트를 매칭한다. 스프링 AOP에서 가장 많이 사용한다.
  • within: 특정 타입(클래스, 인터페이스) 내의 조인 포인트를 매칭한다.
  • args: 인자가 주어진 타입의 인스턴스인 조인 포인트
  • this: 스프링 빈 객체(스프링 AOP 프록시)를 대상으로 하는 조인 포인트
  • target: Target 객체(스프링 AOP 프록시가 가리키는 실제 대상)를 대상으로 하는 조인 포인트
  • @target: 실행 객체의 클래스에 주어진 타입의 애노테이션이 있는 조인 포인트
  • @within: 주어진 애노테이션이 있는 타입 내 조인 포인트
  • @annotation: 주어진 애노테이션을 가지고 있는 메서드를 조인 포인트로 매칭
  • @args: 전달된 실제 인수의 런타임 타입이 주어진 타입의 애노테이션을 갖는 조인 포인트
  • bean: 스프링 전용 포인트컷 지시자, 빈의 이름으로 포인트컷을 지정한다.

 

말로만 보면 이해하기가 정말 난해하다. 그래서 코드로 하나씩 뜯어보자. execution이 가장 많이 사용되고 나머지는 거의 사용하지 않는다. 따라서 execution을 중점적으로 이해해보자.

 

 

필요 데이터 만들기

ClassAop.java

package com.example.aop.member.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE) // Class, Interface 에다가 붙이는 애노테이션인 경우 ElementType.TYPE 을 사용한다.
// RetentionPolicy.RUNTIME 은 실제 RUNTIME 일 때에도 이 애노테이션이 살아있는 경우를 말한다.
// RUNTIME 말고 SOURCE 란 것도 있는데 이건 컴파일하면 컴파일된 파일은 이 애노테이션이 사라져버린다. 그래서 동적으로 이 애노테이션을 읽을 수 없다. 우리가 원하는게 아니다.
@Retention(RetentionPolicy.RUNTIME)
public @interface ClassAop {

}

 

MethodAop.java

package com.example.aop.member.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodAop {
    String value();
}

 

우선, 두 개의 애노테이션을 만들었다. 하나는 클래스 레벨에 달 애노테이션이고 하나는 메서드 레벨에 달 애노테이션이다.

애노테이션을 만드려면 기본적으로 두 개의 애노테이션이 필요하다. @Target, @Retention.

 

@Target은 이 애노테이션이 어디에 달릴지를 설명하는 애노테이션이다. ElementType.TYPE으로 설정하면 클래스 또는 인터페이스에 레벨에 적용할 애노테이션이고 ElementType.METHOD는 메서드 레벨에 적용할 애노테이션이다. 

 

@Retention은 이 애노테이션이 살아있는 레벨을 말한다고 보면 된다. RetentionPolicy.RUNTIME으로 설정하면 런타임에도 해당 애노테이션은 살아 있는 상태로 남아있다. 그래서, 동적으로 애노테이션을 읽을 수 있다. RUNTIME말고 SOURCE도 있는데 이는 컴파일하면 컴파일된 파일에서 애노테이션이 보이지 않고 사라진다. 그래서 동적으로 이 애노테이션을 읽을 수 없다. 

 

그리고 MethodAop 애노테이션은 value() 라는 값을 가질 수 있다. 값의 형태는 문자열이다.

 

MemberService.java

package com.example.aop.member;

public interface MemberService {
    String hello(String param);
}

 

MemberServiceImpl.java

package com.example.aop.member;

import com.example.aop.member.annotation.ClassAop;
import com.example.aop.member.annotation.MethodAop;
import org.springframework.stereotype.Component;

@ClassAop
@Component
public class MemberServiceImpl implements MemberService {

    @Override
    @MethodAop(value = "test value")
    public String hello(String param) {
        return "ok";
    }

    public String internal(String param) {
        return "ok";
    }

    public String twoParams(String param1, String param2) {
        return "ok";
    }
}

 

이번엔 인터페이스와 그 인터페이스를 구현한 구체 클래스를 만들었다. 간단하게 하나의 메서드를 가지는 인터페이스(MemberService)와 그를 구현한 MemberServiceImpl이 있고, 이 구체 클래스는 @ClassAop 애노테이션을 달았다. 그리고 이 구체 클래스 내부에 hello(String param)은 @MethodAop 애노테이션이 달려있다. 

 

ExecutionTest.java

package com.example.aop.pointcut;

import com.example.aop.member.MemberServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;

import java.lang.reflect.Method;

import static org.assertj.core.api.Assertions.*;

@Slf4j
public class ExecutionTest {

    AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
    Method helloMethod;

    @BeforeEach
    public void init() throws NoSuchMethodException {
        helloMethod = MemberServiceImpl.class.getMethod("hello", String.class); // method 이름이 hello, 파라미터의 타입이 String
    }
}

 

테스트 코드다. 리플렉션을 이용해서 구현한 MemberServiceImpl의 hello 메서드를 가져온다. 각 테스트의 실행마다 그 바로 직전에 리플렉션을 활용해서 메서드를 가져오기 위해 @BeforeEach를 사용했다. 

 

AspectJExpressionPointcut은 포인트컷 표현식을 처리해주는 클래스다. 여기에 포인트컷 표현식을 지정하면 된다. 이 클래스는 상위에 Pointcut 인터페이스를 가진다. 

 

 

execution

가장 중요한 포인트컷 지시자이다. 이 execution은 다음과 같이 사용한다.

execution(접근제어자? 반환타입 선언타입?메서드이름(파라미터) 예외?)

 

execution은 메서드 실행 조인 포인트를 매칭한다. 그래서 결국 모든 메서드들 중 이 표현식에 일치하는 메서드들이 AOP로 적용된다. 위 표현 방식에서 '?'가 있는 것은 생략이 가능하다는 뜻이다.

 

그럼 하나씩 천천히 알아보자. 가장 정확한(자세한) 포인트 컷으로 표현해보자. 

 

가장 정확한(자세한) 포인트 컷

execution(public String com.example.aop.member.MemberServiceImpl.hello(String))
  • 접근제어자?: public
  • 반환 타입: String
  • 선언 타입?: com.example.aop.member.MemberServiceImpl
  • 메서드이름: hello
  • 파라미터: (String)
  • 예외?: 생략

 

이렇게 예외를 제외하고 모든 키워드를 작성했다. hello 메서드에 예외는 없기 때문에 제외했다.

이렇게 포인트컷을 지정하고 해당 포인트컷과 hello 메서드가 매치하는지 확인하는 테스트 코드를 작성해보자.

@Test
void exactMatch() {
    pointcut.setExpression("execution(public String com.example.aop.member.MemberServiceImpl.hello(String))");

    assertThat(pointcut.matches(helloMethod, MemberServiceImpl.class)).isTrue();
}

 

결과는 당연히 테스트가 통과한다. 

 

가장 많이 생략한 포인트 컷

execution(* *(..))

 

  • 접근제어자?: 생략
  • 반환 타입: *
  • 선언 타입?: 생략
  • 메서드이름: *
  • 파라미터: (..)
  • 예외?: 생략

'*'은 와일드카드로 모든것을 허용한다는 의미로 받아들이면 될 것 같다. 여기서 생략을 할 수 없는 필수 키워드인 반환 타입, 메서드명, 파라미터만을 작성했다. 반환 타입은 전체(*)이며 메서드명 또한 어떠한 것도 상관 없다는 의미의 '*'이고 파라미터는 어떤 파라미터라도 상관없다는 의미의 (..)를 사용했다. (..)는 파라미터가 없거나 여러개거나 한개거나 어떠한 상태여도 상관이 없다는 의미이다.

 

이런 포인트컷을 사용해서 메서드가 일치하는지 확인해보자.

@Test
void allMatch() {
    pointcut.setExpression("execution(* *(..))");

    assertThat(pointcut.matches(helloMethod, MemberServiceImpl.class)).isTrue();
}

 

결과는 당연히 테스트 통과한다.

 

메서드 이름 매칭 관련 포인트 컷

메서드 이름과 관련된 포인트 컷을 여러개 확인해보자. 메서드 이름에도 '*'를 사용할 수 있다.

@Test
void nameMatch() {
    pointcut.setExpression("execution(* hello(..))");

    assertThat(pointcut.matches(helloMethod, MemberServiceImpl.class)).isTrue();
}

@Test
void nameWildcardMatch() {
    pointcut.setExpression("execution(* hel*(..))");

    assertThat(pointcut.matches(helloMethod, MemberServiceImpl.class)).isTrue();
}

@Test
void nameWildcardMatch2() {
    pointcut.setExpression("execution(* *el*(..))");

    assertThat(pointcut.matches(helloMethod, MemberServiceImpl.class)).isTrue();
}

@Test
void notNameMatch() {
    pointcut.setExpression("execution(* notMatched(..))");

    assertThat(pointcut.matches(helloMethod, MemberServiceImpl.class)).isFalse();
}

 

 

패키지 매칭 관련 포인트 컷

패키지 이름과 관련된 포인트 컷도 여러개 확인해보자. 주의할 점은 하위 패키지 전부를 허용하고 싶을 땐 '..'을 사용해야 한다. (점 두개)

@Test
void packageExactMatch() {
    pointcut.setExpression("execution(* com.example.aop.member.MemberServiceImpl.hello(..))");

    assertThat(pointcut.matches(helloMethod, MemberServiceImpl.class)).isTrue();
}

@Test
void packageExactMatch2() {
    pointcut.setExpression("execution(* com.example.aop.member.*.*(..))");

    assertThat(pointcut.matches(helloMethod, MemberServiceImpl.class)).isTrue();
}

@Test
void packageNotMatch() {
    // 패키지에서 (.)은 정확히 그 위치. 즉, 아래같은 경우 com.example.aop 딱 그 위치를 말한다.
    pointcut.setExpression("execution(* com.example.aop.*.*(..))");

    assertThat(pointcut.matches(helloMethod, MemberServiceImpl.class)).isFalse();
}

@Test
void subPackageMatch() {
    // 패키지에서 하위 패키지까지 몽땅 포함하려면 (..)이어야 한다.
    pointcut.setExpression("execution(* com.example.aop..*.*(..))");

    assertThat(pointcut.matches(helloMethod, MemberServiceImpl.class)).isTrue();
}

@Test
void subPackageMatch2() {
    pointcut.setExpression("execution(* com.example.aop.member..*.*(..))");

    assertThat(pointcut.matches(helloMethod, MemberServiceImpl.class)).isTrue();
}

 

packageNotMatch()를 확인해보면 com.example.aop.*.*(..)로 되어 있는데 이는 하위 패키지도 포함하는게 아니다. 즉, 정확히 com.example.aop의 모든 타입(인터페이스, 클래스)의 모든 메서드를 지정하는 포인트 컷이다. 하위 패키지도 포함하려면 subPackageMatch()처럼 com.example.aop..*.*(..)로 작성해야 한다. 

 

타입 매칭 포인트 컷 

타입 정보에 대한 매치 조건이다.

@Test
void typeExactMatch() {
    pointcut.setExpression("execution(* com.example.aop.member.MemberServiceImpl.*(..))");

    assertThat(pointcut.matches(helloMethod, MemberServiceImpl.class)).isTrue();
}

 

이처럼 정확히 패키지 + 타입(클래스)가 일치하게 포인트컷을 지정할 수 있다. 근데 한가지 조심할 게 있다. 부모 타입은 어떻게 될까?

그러니까 MemberServiceImpl은 상위에 MemberService 인터페이스가 있다. 그럼 포인트컷 표현식에 부모 타입을 작성했을 때 저 hello 메서드는 포인트컷 조건에 만족할까? 결론부터 말하면 만족한다.

@Test
void typeMatchSuperType() {
    // 상위 타입으로 expression 을 설정
    pointcut.setExpression("execution(* com.example.aop.member.MemberService.*(..))");

    // pointcut 은 상위 타입이고 상위 타입이 가지고 있는 메서드면 자식 메서드도 역시 가능하다. 이유는 자식은 부모에 들어갈 수 있으니까.
    assertThat(pointcut.matches(helloMethod, MemberServiceImpl.class)).isTrue();
}

자식은 부모에 들어가는 게 가능하기 때문에, 포인트컷 표현식을 부모로 설정하면 자식 클래스들은 포인트컷을 만족한다. 단, 인터페이스에서 선언된 메서드에 한하여. 이 말은 무슨말이냐면 부모일지언정 부모에 선언된 메서드가 아니라 자식 내부적으로만 가지고 있는 메서드는 포인트컷을 만족하지 못한다는 말이다.

 

위에서 MemberService와 MemberServiceImpl을 보면 부모인 인터페이스에는 hello 메서드만 있고 internal은 없다. 자식인 구체 클래스에는 internal 이라는 내부 메서드가 있다. 이 땐 부모 타입으로 포인트컷을 지정하면 자식 내부적으로만 가지고 있는 메서드에는 포인트 컷 조건이 만족하지 않는다.

@Test
void typeMatchInternal() throws NoSuchMethodException {
    // 상위 타입으로 expression 을 설정
    pointcut.setExpression("execution(* com.example.aop.member.MemberService.*(..))");

    Method internalMethod = MemberServiceImpl.class.getMethod("internal", String.class);

    // 상위 타입으로 pointcut 의 expression 을 설정한 경우, 상위 타입이 가지고 있는 메서드만 가능하다.
    assertThat(pointcut.matches(internalMethod, MemberServiceImpl.class)).isFalse();
}

 

 

파라미터 매칭 포인트 컷

이 파라미터 매칭 조건은 다음 예시를 보면 하나하나 다 이해가 가능할 것이다.

/**
 * 모든 메서드 중 파라미터가 String 타입 하나 인 것들을 매치
 * */
@Test
void argsMatch() {
    pointcut.setExpression("execution(* *(String))");

    assertThat(pointcut.matches(helloMethod, MemberServiceImpl.class)).isTrue();
}

/**
 * 모든 메서드 중 파라미터가 없는 것들을 매치
 * */
@Test
void argsMatchNoArgs() {
    pointcut.setExpression("execution(* *())");

    assertThat(pointcut.matches(helloMethod, MemberServiceImpl.class)).isFalse();
}

/**
 * 모든 메서드 중 모든 타입을 허용하지만 딱 한 개의 파라미터만 허용
 * */
@Test
void argsMatchWildCard() {
    pointcut.setExpression("execution(* *(*))");

    assertThat(pointcut.matches(helloMethod, MemberServiceImpl.class)).isTrue();
}

/**
 * 모든 메서드 중 모든 타입, 모든 개수의 파라미터를 허용
 * */
@Test
void argsMatchAll() {
    pointcut.setExpression("execution(* *(..))");

    assertThat(pointcut.matches(helloMethod, MemberServiceImpl.class)).isTrue();
}

/**
 * 모든 메서드 중 파라미터가 String 타입으로 시작하고 그 이후는 모든 타입, 모든 개수의 파라미터를 허용 또는 없어도 된다.
 * */
@Test
void argsMatchComplex() {
    pointcut.setExpression("execution(* *(String, ..))");

    assertThat(pointcut.matches(helloMethod, MemberServiceImpl.class)).isTrue();
}

/**
 * 모든 메서드 중 파라미터가 딱 두개이면서 둘 다 String 타입인 것
 * */
@Test
void argsMatchComplexExactly() throws NoSuchMethodException {
    pointcut.setExpression("execution(* *(String, String))");

    Method twoParamsMethod = MemberServiceImpl.class.getMethod("twoParams", String.class, String.class);

    assertThat(pointcut.matches(twoParamsMethod, MemberServiceImpl.class)).isTrue();
}

/**
 * 모든 메서드 중 파라미터가 딱 두개이면서 첫번째는 String, 두번째는 모든 타입
 * */
@Test
void argsMatchComplexExactly2() throws NoSuchMethodException {
    pointcut.setExpression("execution(* *(String, *))");

    Method twoParamsMethod = MemberServiceImpl.class.getMethod("twoParams", String.class, String.class);

    assertThat(pointcut.matches(twoParamsMethod, MemberServiceImpl.class)).isTrue();
}

 

 

within

within 지시자는 특정 타입 내의 조인 포인트들로 매칭을 제한한다. 이 말만 보면 무슨말인지 잘 모르겠다. 쉽게 말하면 작성한 타입이 매칭되면 그 안의 메서드들이 자동으로 매치된다.

 

WithinTest.java

package com.example.aop.pointcut;

import com.example.aop.member.MemberServiceImpl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;

import java.lang.reflect.Method;

import static org.assertj.core.api.Assertions.*;

/**
 * Within은 타입(클래스, 인터페이스)을 지정하면 그 안에 메서드는 모두 매치가 되게 하는 방법
 * */
public class WithinTest {

    AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
    Method helloMethod;

    @BeforeEach
    public void init() throws NoSuchMethodException {
        helloMethod = MemberServiceImpl.class.getMethod("hello", String.class); // method 이름이 hello, 파라미터의 타입이 String
    }

    @Test
    void withinExactly() throws NoSuchMethodException {
        pointcut.setExpression("within(com.example.aop.member.MemberServiceImpl)");

        Method internal = MemberServiceImpl.class.getMethod("internal", String.class);

        assertThat(pointcut.matches(helloMethod, MemberServiceImpl.class)).isTrue();
        assertThat(pointcut.matches(internal, MemberServiceImpl.class)).isTrue();
    }

    @Test
    void withinWildCard() {
        pointcut.setExpression("within(com.example.aop.member.*Service*)");

        assertThat(pointcut.matches(helloMethod, MemberServiceImpl.class)).isTrue();
    }

    @Test
    void withinSubPackage() {
        pointcut.setExpression("within(com.example.aop..*)");

        assertThat(pointcut.matches(helloMethod, MemberServiceImpl.class)).isTrue();
    }

    @Test
    @DisplayName("타겟의 정확하게 타입에만 직접 적용해야 한다")
    void withinSuperTypeFalse() {
        // 상위 타입으로 설정하면 within 은 안된다. 정확히 그 타입으로 지정해야 한다. execution 은 이게 가능했는데 within 은 아니다.
        pointcut.setExpression("within(com.example.aop.member.MemberService)");

        assertThat(pointcut.matches(helloMethod, MemberServiceImpl.class)).isFalse();
    }
}

 

withinExactly()를 보면 within(com.example.aop.member.MemberServiceImpl)이라고 되어 있다. 이렇게 하면 MemberServiceImpl 클래스 내 메서드들이 이 포인트컷에 매칭된다.

 

주의

그러나, 주의할 부분이 있다. 표현식에 부모 타입을 지정하면 안된다. 정확하게 타입이 맞아야 한다. 이 점이 execution과 다른 점이다.

 

 

args

인자가 주어진 타입의 인스턴스인 조인 포인트로 매칭. 말이 또 어려운데 쉽게 말해 파라미터가 매치되는 녀석들이 다 조인 포인트가 된다고 보면 된다. 아래 코드를 보면 바로 이해가 될 것이다.

 

ArgsTest.java

package com.example.aop.pointcut;

import com.example.aop.member.MemberServiceImpl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;

import java.lang.reflect.Method;

import static org.assertj.core.api.Assertions.assertThat;

public class ArgsTest {

    Method helloMethod;

    @BeforeEach
    public void init() throws NoSuchMethodException {
        helloMethod = MemberServiceImpl.class.getMethod("hello", String.class); // method 이름이 hello, 파라미터의 타입이 String
    }

    private AspectJExpressionPointcut pointcut(String expression) {
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(expression);

        return pointcut;
    }

    @Test
    void args() {
        // hello(String)과 매칭
        assertThat(pointcut("args(String)").matches(helloMethod, MemberServiceImpl.class)).isTrue();
        assertThat(pointcut("args(Object)").matches(helloMethod, MemberServiceImpl.class)).isTrue();
        assertThat(pointcut("args()").matches(helloMethod, MemberServiceImpl.class)).isFalse();
        assertThat(pointcut("args(..)").matches(helloMethod, MemberServiceImpl.class)).isTrue();
        assertThat(pointcut("args(*)").matches(helloMethod, MemberServiceImpl.class)).isTrue();
        assertThat(pointcut("args(String, ..)").matches(helloMethod, MemberServiceImpl.class)).isTrue();
    }

    @Test
    void argsVsExecution() {
        // Args (Args 는 상위 타입을 허용한다)
        assertThat(pointcut("args(String)")
                .matches(helloMethod, MemberServiceImpl.class)).isTrue();
        assertThat(pointcut("args(java.io.Serializable)")
                .matches(helloMethod, MemberServiceImpl.class)).isTrue();
        assertThat(pointcut("args(Object)")
                .matches(helloMethod, MemberServiceImpl.class)).isTrue();

        // Execution (Execution 은 상위 타입을 허용하지 않고 딱 정확하게 선언해야 한다)
        assertThat(pointcut("execution(* *(String))")
                .matches(helloMethod, MemberServiceImpl.class)).isTrue();
        assertThat(pointcut("execution(* *(java.io.Serializable))")
                .matches(helloMethod, MemberServiceImpl.class)).isFalse();
        assertThat(pointcut("execution(* *(Object))")
                .matches(helloMethod, MemberServiceImpl.class)).isFalse();
    }
}

 

args()를 보면, pointcut으로 args(String), args(Object),... 이렇게 되어 있다. 즉, 이 파라미터와 일치하는 메서드를 매치시키는 방법. 근데 이 args는 execution과 다르게 부모 타입도 허용한다. 즉, 파라미터의 타입이 String인 메서드라면 args(Object)로 해도 매치가 된다는 뜻이다. 

 

참고로 args 지시자는 단독으로 사용되기 보다는 파라미터 바인딩에서 주로 사용된다. 

 

 

@target, @within

정의

@target: 실행 객체의 클래스에 주어진 타입의 애노테이션이 있는 조인 포인트

@within: 주어진 애노테이션이 있는 타입 내 조안 포인트

 

사실 그렇게 중요하지도 않고 정의만 보고서는 뭔 말인지 감이 잘 안오지만 코드로 보면 간단하다. 우선 둘 모두 타입에 있는 애노테이션으로 AOP 적용 여부를 판단한다.

@target(hello.aop.member.annotation.ClassAop)
@within(hello.aop.member.annotation.ClassAop)

 

@ClassAop
class Target {

}

 

여기서 두 개의 차이는 다음과 같다. 

@target은 애노테이션이 달린 클래스의 부모 클래스의 메서드까지 어드바이스를 전부 적용하고, @within은 자기 자신의 클래스에 정의된 메서드만 어드바이스를 적용한다. 

 

 

그래서 한 문장으로 정리를 하자면 @target, @within 둘 모두 애노테이션으로 AOP를 적용하는데 @target의 경우 애노테이션이 달린 클래스와 그 상위 클래스의 메서드 모두에게 어드바이스를 적용하고 @within의 경우 애노테이션이 달린 클래스의 메서드에만 어드바이스를 적용한다.

 

AtTargetAtWithinTest.java

package com.example.aop.pointcut.annotation;

import com.example.aop.member.annotation.ClassAop;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;


/**
 * 클래스에 붙이는 애노테이션을 기반으로 포인트컷을 만들 땐 @target, @within 을 사용할 수 있다.
 * */
@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() {
            log.info("[parentMethod] Start");
        }
    }

    @ClassAop
    static class Child extends Parent {
        public void childMethod() {
            log.info("[childMethod] Start");
        }
    }

    @Aspect
    static class AtTargetAtWithinAspect {

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

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

        // 참고로 @target, @args, args 이런 포인트컷 지시자는 단독으로 사용하면 안된다. 위 에제에서도 execution 과 같이 사용했는데
        // 그 이유는 스프링이 이런 포인트컷 지시자가 있으면 모든 스프링 빈에 AOP 를 적용하려고 시도하는데 스프링이 내부에서 사용하는 빈 중에는 final 로
        // 지정된 빈들도 있기 때문에 오류가 발생할 수 있다.
    }
}

 

 

우선 체크포인트는 다음과 같다.

 

  • Child, Parent 클래스가 있다. Child 클래스는 상위 클래스로 Parent 클래스가 있다. 
  • 두 클래스를 모두 스프링 빈으로 등록한다.
  • 에스팩트가 있고 두 개의 어드바이저가 있다. 하나는 @target 하나는 @within으로 만들어진 포인트컷이다.
  • @target@within 모두 같은 애노테이션인 ClassAop 애노테이션이 달린 클래스를 찾아 AOP로 적용한다.
  • 이 에스팩트 역시 스프링 빈으로 등록한다.
  • 스프링 빈으로 등록한 Child 클래스를 테스트 코드에서는 주입받는다.
  • 주입받은 Child 클래스의 childMethod(), parentMethod()를 각각 호출한다.
  • 결과는 childMethod() 호출 시, @target과 @within 모두 적용된다. parentMethod() 호출 시 @target만 적용되고 @within은 적용되지 않는다.

 

주의

args, @args, @target 이 포인트컷 지시자는 단독으로 사용할 수 없다. 그 이유는 이런 포인트컷이 있으면 스프링은 모든 스프링 빈에 AOP를 적용하려고 시도한다. 문제는 모든 스프링 빈에 AOP를 적용하려고 하면 스프링이 내부에서 사용하는 빈 중에는 final로 지정된 빈들도 있기 때문에 오류가 발생한다. 따라서 이런 포인트컷 지시자는 단독으로 사용하면 안되고 최대한 적용 대상을 축소하는 표현식과 함께 사용해야 한다.

 

 

@annotation, @args

@annotation: 메서드가 주어진 애노테이션을 가지고 있는 조인 포인트를 매칭

@args: 전달된 실제 인수의 런타임 타입이 주어진 타입의 애노테이션을 갖는 조인 포인트

 

@annotation은 종종 사용되니 이것을 집중해서 보자.

@annotation(hello.aop.member.annotation.MethodAop)

 

쉽게 말해 메서드에 지정한 애노테이션이 있으면 매칭한다. 다음 코드처럼.

public class MemberServiceImpl {
     @MethodAop("test value")
     public String hello(String param) {
         return "ok";
     }
}

 

AtAnnotationTest.java

package com.example.aop.pointcut.annotation;

import com.example.aop.member.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;


/**
 * 메서드에 붙이는 애노테이션을 기반으로 포인트컷을 만들 때 사용되는 @annotation
 *
 * ⭐이거는 좀 자주 사용된다.
 * */
@Slf4j
@Import(AtAnnotationTest.AtAnnotationAspect.class)
@SpringBootTest
public class AtAnnotationTest {

    @Autowired
    MemberService memberService;

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

    @Aspect
    static class AtAnnotationAspect {

        @Around("@annotation(com.example.aop.member.annotation.MethodAop)")
        public Object doAtAnnotation(ProceedingJoinPoint joinPoint) throws Throwable {
            log.info("[@annotation] {}", joinPoint.getSignature());
            return joinPoint.proceed();
        }
    }
}

 

위 코드에서 에스팩트를 보면 @Around의 포인트컷 지시자로 @annotation을 사용한다. MethodAop 라는 애노테이션이 달린 메서드에 이 AOP가 적용된다. 그리고 만든 MemberServiceImpl의 hello()는 @MethodAop 애노테이션이 있다. 따라서 테스트 success()는 AOP가 적용된 hello()가 호출된다.

 

 

bean

스프링 전용 포인트컷 지시자. 빈의 이름으로 지정한다.

bean(orderService) || bean(*Repository)

 

바로 예시 코드로 확인해보자. 그리고 이 지시자 역시 자주 사용되는 지시자는 아니다.

 

BeanTest.java

package com.example.aop.pointcut;

import com.example.aop.order.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;

@Slf4j
@Import(BeanTest.BeanAspect.class)
@SpringBootTest
public class BeanTest {

    @Autowired
    OrderService orderService;

    @Test
    void success() {
        orderService.orderItem("item");
    }

    @Aspect
    static class BeanAspect {

        @Around("bean(orderService) || bean(*Repository)")
        public Object doLog(ProceedingJoinPoint joinPoint) throws Throwable {
            log.info("[bean] {}", joinPoint.getSignature());
            return joinPoint.proceed();
        }
    }
}

 

BeanAspect를 보면 orderService라는 bean 또는 *Repository라는 bean을 포인트컷의 조건으로 어드바이스를 만든 모습을 확인할 수 있다. 그 후 테스트 success()는 orderService의 orderItem()을 호출한다. 그러므로 저 어드바이스가 적용된다.

 

 

매개변수 전달 (중요⭐️)

어드바이스 쪽에서 메서드의 파라미터를 전달받고 싶을 땐 어떻게 해야 할까? 예를 들어 다음 코드를 보자.

orderService.orderItem("item");

 

이런 코드가 있을 때, 어드바이스가 저 파라미터 'item'을 어떻게 받을 수 있을까? 이를 알아보자.

 

우선 이 경우 joinPoint를 사용하거나 다음 포인트컷 지시자를 활용한다.

  • args

가장 원시적인 방법을 먼저 확인해보자.

 

포인트컷

@Pointcut("execution(* hello.aop.member..*.*(..))")
private void allMember() {}

 

JoinPoint를 활용하기

 

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

 

joinPoint를 활용하면 getArgs() 메서드를 사용할 수 있다. 허나, 이 방법은 배열에서 꺼내는 방식인데 그렇게 좋은 방식은 아닌것 같다.

 

args

@Around("allMember() && args(arg, ..)")
public Object logArgs2(ProceedingJoinPoint joinPoint, Object arg) throws Throwable {
    log.info("[logArgs2]{}, arg = {}", joinPoint.getSignature(), arg);
    return joinPoint.proceed();
}

 

포인트컷 지시자 'args'를 사용한다. args(arg, ..)은 첫번째 파라미터를 받고 그 이후에 파라미터는 있거나 없거나 신경쓰지 않는다는 뜻이다. 그리고 이 arg를 어드바이스의 파라미터로 이름 그대로(arg) 동일하게 받아야 한다. 

 

실제 파라미터의 타입은 String인데 그 상위 타입인 Object로 받아도 무방하다. 

 

위에서 @Around를 사용했는데 @Around는 ProceedingJoinPoint를 반드시 첫번째 파라미터로 받아야 하는 불편함이 있다. 굳이 코드 내에서 실제 객체를 호출하는 코드를 직접 호출해야 하는 경우가 아니라면 다음처럼 더 간략하게 사용할 수 있다.

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

 

이번에는 상위 타입이 아닌 정확히 String으로 받아주었다. 물론 상위 타입도 상관없다.

 

 

@annotation으로 애노테이션이 가지고 있는 값들 꺼내오기

애노테이션 중에는 특정 값을 가지는 애노테이션이 있다. 다음이 그 예시다.

package com.example.aop.member.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodAop {
    String value();
}

 

 

value() 라는 값을 가지는 애노테이션이다.

 

package com.example.aop.member;

import com.example.aop.member.annotation.ClassAop;
import com.example.aop.member.annotation.MethodAop;
import org.springframework.stereotype.Component;

@ClassAop
@Component
public class MemberServiceImpl implements MemberService {

    @Override
    @MethodAop(value = "test value")
    public String hello(String param) {
        return "ok";
    }

    public String internal(String param) {
        return "ok";
    }

    public String twoParams(String param1, String param2) {
        return "ok";
    }
}

 

그 애노테이션의 value 값으로 'test value'라는 값을 가지는 hello()가 있을 때 이 값은 어떻게 가져올까?

 

다음처럼 @annotation을 활용해서 애노테이션을 파라미터로 받으면 된다.

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

여기서, @annotation(annotation)이라고 썼으면 파라미터에서도 'annotation'이라는 이름으로 받아야 한다. 만약 @annotation(methodAop)로 썼으면 파라미터도 'methodAop'라는 이름으로 받으면 된다. 

 

그리고 한가지 더, 원래는 @annotation 지시자를 사용할 때 패키지명부터 쭉 써줘야 한다. 예를 들면 이렇게.

@annotation(com.example.aop.member.annotation.MethodAop)

 

근데 위에서처럼 저렇게 파라미터로 애노테이션 타입을 명시하면 이름으로 치환할 수 있다.

 

 

this, target

솔직히 이게 중요한지는 모르겠다. 근데 내용이 은근히 어렵다. 그래서 굳이라는 생각이 들지만 한번 정리해보겠다.

 

  • this: 스프링 빈 객체(스프링 AOP 프록시)를 대상으로 하는 조인 포인트
  • target: Target 객체(스프링 AOP 프록시가 가리키는 실제 대상)를 대상으로 하는 조인 포인트

 

설명

  • this, target은 다음과 같이 적용 타입 하나를 정확하게 지정해야 한다.
  • '*' 같은 패턴을 사용할 수 없다.
  • 부모 타입을 허용한다.
this(hello.aop.member.MemberService)
target(hello.aop.member.MemberService)

 

똑같이 생겨가지고 무슨 차이가 있을까?

 

스프링에서 AOP를 적용하면 실제 target 객체 대신에 프록시 객체가 스프링 빈으로 등록된다. 여기서,

  • this는 스프링 빈으로 등록되어 있는 프록시 객체를 대상으로 포인트컷을 매칭한다.
  • target은 실제 target 객체를 대상으로 포인트컷을 매칭한다.

그러니까 다음 코드 예시를 보면,

this(hello.aop.member.MemberService)
target(hello.aop.member.MemberService)

 

똑같이 MemberService를 조건으로 입력해도 this는 스프링 빈으로 등록된 프록시를, target은 스프링 빈으로 등록된 프록시가 참조하는 실제 객체를 바라본다는 뜻인데 이게 뭐 큰 의미가 있고 달라지나 싶을 수 있다. 그러나, JDK 동적 프록시와 CGLIB의 프록시 생성 방식이 다르기 때문에 차이점이 발생할 수 있다.

 

JDK 동적 프록시

이 방식은 인터페이스가 필수이고 인터페이스를 구현한 프록시 객체를 생성한다. 다음이 그 그림이다.

 

 

그럼 이 방식으로 프록시를 만들 때 this와 target 지시자가 어떻게 다른지 보자.

 

MemberService 인터페이스 지정

  • this(hello.aop.member.MemberService)
    • proxy 객체를 보고 판단한다. this는 부모 타입을 허용한다. 프록시는 인터페이스인 MemberService를 참조하므로 AOP가 적용된다.
  • target(hello.aop.member.MemberService)
    • target 객체를 보고 판단한다. target은 부모 타입을 허용한다. target이 상속받는 MemberService가 있으므로 AOP가 적용된다.

MemberServiceImpl 구체 클래스 지정

  • this(hello.aop.member.MemberServiceImpl)
    • proxy 객체를 보고 판단한다. 프록시 객체의 부모는 MemberService 인터페이스이다. 인터페이스 위에 있는 것은 없다. MemberServiceImpl에 대한 정보를 아예 알 수 없으므로 AOP 적용 대상이 아니다.
  • target(hello.aop.member.MemberServiceImpl)
    • target 객체를 보고 판단한다. target은 바로 MemberServiceImpl 구체 클래스이므로 AOP 적용 대상이다.

 

결론은 JDK 동적 프록시는 this로 구체 클래스를 받으면 AOP 적용 대상이 아니게 된다. 반면 CGLIB는 어떨까?

 

 

CGLIB 프록시

 

MemberService 인터페이스 지정

  • this(hello.aop.member.MemberService)
    • this는 proxy 객체를 바라본다. 프록시 객체는 구체 클래스인 MemberServiceImpl을 상속받는다. 그리고 이 구체 클래스의 부모인 MemberService 인터페이스가 있다. this는 부모 타입을 허용하므로 AOP 적용 대상이다.
  • target(hello.aop.member.MemberService)
    • target은 실제 target 객체를 바라본다. target 객체인 MemberServiceImpl의 부모인 MemberService가 있다. target은 부모 타입을 허용하므로 AOP 적용 대상이다.

MemberServiceImpl 구체 클래스 지정

  • this(hello.aop.member.MemberServiceImpl)
    • this는 proxy 객체를 바라본다. 프록시 객체는 구체 클래스인 MemberServiceImpl을 상속받는다. this는 부모 타입을 허용하므로 AOP 적용 대상이다.
  • target(hello.aop.member.MemberServiceImpl)
    • target은 실제 target 객체를 바라본다. target 객체가 MemberServiceImpl이므로 AOP 적용 대상이다.

 

결론은 CGLIB 프록시는 모든 경우에 AOP 적용 대상이 된다. 그리고 스프링은 기본으로 CGLIB로 프록시를 만들어낸다. 

 

 

실제로 AOP 적용을 위 설명처럼 하는지 확인해보자.

 

ThisTargetTest.java

package com.example.aop.pointcut;

import com.example.aop.member.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;

@Slf4j
@Import(ThisTargetTest.ThisTargetAspect.class)
@SpringBootTest
public class ThisTargetTest {

    @Autowired
    MemberService memberService;

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

    @Aspect
    static class ThisTargetAspect {

        @Around("this(com.example.aop.member.MemberService)")
        public Object doThisInterface(ProceedingJoinPoint joinPoint) throws Throwable {
            log.info("[this-interface] {}", joinPoint.getSignature());
            return joinPoint.proceed();
        }

        @Around("target(com.example.aop.member.MemberService)")
        public Object doTargetInterface(ProceedingJoinPoint joinPoint) throws Throwable {
            log.info("[target-interface] {}", joinPoint.getSignature());
            return joinPoint.proceed();
        }

        @Around("this(com.example.aop.member.MemberServiceImpl)")
        public Object doThisConcrete(ProceedingJoinPoint joinPoint) throws Throwable {
            log.info("[this-impl] {}", joinPoint.getSignature());
            return joinPoint.proceed();
        }

        @Around("target(com.example.aop.member.MemberServiceImpl)")
        public Object doTargetConcrete(ProceedingJoinPoint joinPoint) throws Throwable {
            log.info("[target-impl] {}", joinPoint.getSignature());
            return joinPoint.proceed();
        }
    }
}

 

에스팩트에 4개의 어드바이저가 있다. 위 설명 대로 this에 인터페이스, 구체 클래스를 target에 인터페이스, 구체 클래스를 적용했을 때 AOP가 적용되는지에 대한 내용이다. 스프링은 기본으로 CGLIB 프록시로 프록시를 만들어내는데 그 설정 값은 다음과 같다.

spring:
  aop:
    proxy-target-class: true # true = CGLIB 를 기본으로 / false = JDK 동적 프록시를 기본으로

 

이 상태로 success() 테스트를 실행하면 모든 어드바이저가 적용된다.

 

이제 JDK 동적 프록시를 스프링 기본 프록시로 설정해보자. 

spring:
  aop:
    proxy-target-class: false

 

 

this-impl 로그가 찍히지 않았음을 확인할 수 있다.

 

 

728x90
반응형
LIST

'Spring Advanced' 카테고리의 다른 글

AOP (Part.2)  (0) 2024.01.02
AOP(Aspect Oriented Programming)  (0) 2023.12.29
AOP와 @Aspect, @Around  (0) 2023.12.29
빈 후처리기(BeanPostProcessor)  (2) 2023.12.27
Advisor, Advice, Pointcut  (0) 2023.12.15