AOP Order

dktlsk6·2022년 6월 23일
0
post-thumbnail

AOP Order

Spring AOP는 순서를 지정할 수 있다. 하지만 method 단위에서는 불가하고 Class 단위에 적용 가능하다.

아래는 잘못된 예시이다. 이렇게 설정할 경우 순서 지정을 되지 않는다.

@Order(2)
@Around("allOrder()")
public Object doLog(ProceedingJoinPoint joinPoint) throws Throwable{
        log.info("[log] {}", joinPoint.getSignature());
        return joinPoint.proceed();
}

    // hello.aop.order 하위패키지면서 class name *Service
    @Order(1)
    @Around("allOrder() && allService()")
    public Object doTransaction(ProceedingJoinPoint joinPoint) throws Throwable{
        try{
            log.info("[transaction start] {}", joinPoint.getSignature());
            Object result = joinPoint.proceed();
            log.info("[transaction commit] {}", joinPoint.getSignature());
            return result;
        }catch (Exception e){
            log.info("[transaction rollback] {}", joinPoint.getSignature());
            throw e;
        }finally {
            log.info("[resource release] {}", joinPoint.getSignature());
        }
    }

아래와 같이 Class 단위에 적용한다면 지정해준 순서대로 AOP가 적용된다.

@Aspect
    @Order(2)
    public static class LogAspect{
        @Around("hello.aop.order.aop.Pointcuts.allOrder()")
        public Object doLog(ProceedingJoinPoint joinPoint) throws Throwable{
            log.info("[log] {}", joinPoint.getSignature());
            return joinPoint.proceed();
        }
    }

    @Aspect
    @Order(1)
    public static class TxAspect{
        // hello.aop.order 하위패키지면서 class name *Service
        @Around("hello.aop.order.aop.Pointcuts.orderAndService()")
        public Object doTransaction(ProceedingJoinPoint joinPoint) throws Throwable{
            try{
                log.info("[transaction start] {}", joinPoint.getSignature());
                Object result = joinPoint.proceed();
                log.info("[transaction commit] {}", joinPoint.getSignature());
                return result;
            }catch (Exception e){
                log.info("[transaction rollback] {}", joinPoint.getSignature());
                throw e;
            }finally {
                log.info("[resource release] {}", joinPoint.getSignature());
            }
        }
    }
profile
개발자로 입사했지만 정체성을 잃어가는중... 다시 준비 시작이다..

0개의 댓글