AOP

임정호·2022년 1월 30일
0

Spring공부

목록 보기
9/10

AOP ( Aspect Oriented Programming )

관점 지향 프로그래밍

MVC 웹 어플리케이션은 Web Layerm Business Layer, Data Layer로 구분.

  • Web Layer : REST API 제공, Client 중심의 로직 적용
  • Business Layer : 내부 정책에 따른 Logic 개발
  • Data Layer : DB및 외부와의 연동 처리

횡단 관심

TimerAop

메서드의 실행시간을 로그에 남기고 싶을 경우, 사용할 수 있는 TimerAop예시.

Timer라는 annotation을 생성하여, @Timer가 붙은 메서드의 실행 시간을 구해보자.

// Timer.java (annotation)

Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Timer {

}
// TimerAop.java

@Aspect
@Component
public class TimerAop {

    @Pointcut("execution(* com.example.aop.controller..*.*(..))")
    public void cut(){}

    @Pointcut("@annotation(com.example.aop.annotation.Timer)")
    private void enableTimer(){    }

    @Around("cut() && enableTimer()")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        var result = joinPoint.proceed();

        stopWatch.stop();

        System.out.println("total time : " + stopWatch.getTotalTimeSeconds());

    }
}

2초 sleep하고 종료하게끔 함

실행이 잘 되는 것을 알 수 있다!

주요 Annotation

@Aspect: AOP를 정의하는 Class에 할당
@Pointcut : aop 기능을 적용시킬 지점을 설정
@Before : 메서드 실행 전에 적용
@After : 메서드가 성공적으로 실행 후, 예외가 발생하더라도 실행
@AfterReturning : 메서드 호출 성공 실행 시
@AfterThrowing : 메서드 호출 실패, 예외 발생 시
@Around : Before / after 모두 제어

0개의 댓글