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

Ch10. 스프링 AOP(구현) - 스프링 AOP 구현(포인트컷 참조)

webmaster 2022. 4. 19. 19:43
728x90

참고로 외부에서 호출할 때는 포인트 컷의 접근 제어자를 public으로 열어두어야 한다.

Pointcut 조합

public class Pointcuts {
    //hello.aop.order 패키지와 하위 패키지
    @Pointcut("execution(* hello.aop.order..*(..))")
    public void allOrder() { } //pointcut signature

    //클래스 이름 패턴이 *Service
    @Pointcut("execution(* *..*Service.*(..))")
    public void allService() {
    }

    //allOrder && allService
    @Pointcut("allOrder() && allService()")
    public void orderAndService(){};
}
  • orderAndService() : allOrder() 포인트컷와 allService() 포인트 컷을 조합해서 새로운 포인트 컷을 만들었다

AspectV4Pointcut

@Slf4j
@Aspect
public class AspectV4Pointcut {

    @Around("hello.aop.order.aop.Pointcuts.allOrder()")
    public Object doLog(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("[log] {}", joinPoint.getSignature());//joinPoint 시그니처
        return joinPoint.proceed();
    }

    @Around("hello.aop.order.aop.Pointcuts.orderAndService()")
    public Object doTransaction(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            log.info("[트랜잭션 시작] {}", joinPoint.getSignature());
            Object result = joinPoint.proceed();
            log.info("[트랜잭션 커밋] {}", joinPoint.getSignature());
            return result;
        }catch (Exception e){
            log.info("[log] {} ", joinPoint.getSignature()); //join point 시그니처
            throw e;
        }finally {
            log.info("[리소스 릴리즈] {}", joinPoint.getSignature());
        }
    }
}
  • 패키 지명을 포함한 클래스 이름과 포인트 컷 시그니처를 모두 지정하면 된다
  • 포인트 컷을 여러 어드바이스에서 함께 사용할 때 이 방법을 사용하면 효과적이다.

실행

@Slf4j
@SpringBootTest
@Import(AspectV4Pointcut.class)
public class AopTest {
	...
}
728x90