Spring Framework의 특징(Advice, Pointcut)

김병수·2022년 10월 18일
0
post-thumbnail

어드바이스(Advice)

조인포인트에서 수행되는 코드. Aspect를 언제 핵심 코드에 적용할지를 정의한다.

어드바이스 순서

어드바이스는 기본적으로 순서를 보장하지 않기 때문에 @Aspect 적용 단위로 org.springframework.core.annotation.@Order 애너테이션을 적용해야 한다. 이는 어드바이스 단위가 아니라 클래스 단위로 적용할 수 있기에 애스팩트를 별도의 클래스로 분리해야 한다.

Advice 종류

Before

  • 조인 포인트 실행 이전해 실행
  • 리턴타입이 void
  • 예외 발생 시, 대상 객체의 메서드가 호출되지 않게 됨
@Before("hello.aop.order.aop.Pointcuts.orderAndService()")
public void doBefore(JoinPoint joinPoint) {
    log.info("[before] {}", joinPoint.getSignature());
}

After returning

  • 조인 포인트가 정상 완류 후 실행
  • returnig 속성에 사용된 이름은 어드바이스 메서드의 매개변수 이름과 일치해야 함
@AfterReturning(value = "hello.aop.order.aop.Pointcuts.orderAndService()", returning = "result")
public void doReturn(JoinPoint joinPoint, Object result) {
    log.info("[return] {} return={}", joinPoint.getSignature(), result);
}

After thowing

  • 메서드가 예외를 던지는 경우에 실행
  • throwing 속성에 사용된 이름은 어드바이스 메서드의 매개변수 이름과 일치해야 함
@AfterThrowing(value = "hello.aop.order.aop.Pointcuts.orderAndService()", throwing = "ex")
public void doThrowing(JoinPoint joinPoint, Exception ex) {
    log.info("[ex] {} message={}", joinPoint.getSignature(), ex.getMessage());
}

After(finally)

  • 조인 포인트의 동작과는 상관없이 실행(예외 처리의 finally와 유사)
  • 리소스 해제 시 사용

Around

  • 메서드 호출 전후에 수행하며 가장 강력한 어드바이스
  • proceed()를 통해 대상을 실행
  • @Around 애너테이션으로 모든 어드바이스 기능 수행이 가능함

Pointcut

조인포인트 중에서 어드바이스가 적용될 위치를 선별하는 기능이다.

Pointcut 표현

@Pointcut("execution(* transfer(..))") // 포인트컷 표현식
private void anyOldTransfer() {} // 포인트컷 서명

포인트컷 지시자에는 여러 종류가 있지만 주로 execution을 사용한다.

표현식 결합
포인트컷 표현식은 &&, ||, !와 같은 연산자들을 사용하여 결합할 수 있다.

@Pointcut("execution(public * *(..))")
private void anyPublicOperation() {}

@Pointcut("within(com.xyz.myapp.trading..*)")
private void inTrading() {}

@Pointcut("anyPublicOperation() && inTrading()")
private void tradingOperation() {} 
profile
BE 개발자를 꿈꾸는 대학생

0개의 댓글