[Spring Framework 특성 살피기] AOP에 대한 이해

2021. 8. 3. 15:35카테고리 없음

728x90
반응형

 

Spring Framework 특성 살피기_ 2. AOP에 대한 이해

AOP(Aspect Of Programming) : 관점 지향적인 프로그래밍

이해

ex1) 일반적인 경우 ex2) 관점 지향적인 프로그래밍 구조
class A{
     method a(){
          안녕안녕
         오늘은 월요일이야
         잘가잘가
     
}
     method b(){
         안녕안녕
         오늘은 금요일이야
         잘가잘가
     
}
}
class A{
     method a(){
         오늘은 월요일이야
     
}
     method b(){
         오늘은 금요일이야
     
}
}

class hiBye{
     method hibye(){
         안녕안녕
         point.execute()
         잘가잘가
     
}
}

- 기존의 코드를 수정하지 않고 새 기능을 추가.
- 수정에 용이

 

AOP구현방법

1. 컴파일 : [A.java -> A.class]과정에 AOP컴파일(AspectJ)을 끼워넣어 진행.

2. 바이트코드 조작 : [A.class -> 메모리]과정에서 클래스로더가 AOP컴파일(AspectJ)을 끼워넣어 진행.

3. 프록시 패턴 : 스프링의 AOP방식. @Transactional 애너테이션으로 구현 가능.

 

@AOP로 스탑와치 예제 만들기

- @LogExecutionTime(다른 이름도 상관 없음) 애너테이션을 만들어 기능으로써 사용해보자.

순서 1.
사용하고 싶은 기능을 임의의 애너테이션명으로 작성
@GetMapping("/owners/find")
@LogExecutionTime
public String initFindForm(Map<String, Object> model) {
      model.put("owner", new Owner());
      return "owners/findOwners";
}
순서 2.
애너테이션 정의 클래스의 뼈대 작성
@Target(ElementType.METHOD) //애너테이션 대상을 METHOD로 설정
@Retention(RetentionPolicy.RUNTIME) //애너테이션 생명주기를 RUNTIME으로 설정
public @interface LogExecutionTime {
}
순서 3.
Bean설정을 위한
Aspect 클래스 작성
@Component //Bean으로 등록되기 위함
@Aspect
public class LogAspect{
      Logger logger = LoggerFactory.getLogger(LogAspect.class);


      @Around(“@annotation(LogExecutionTime)”)
      public Object logExecutionTime(ProceedingJoinPoint joinPoint)
      throws Throwable{

      //joinPoint : logExecution이 쓰일 Target메소드를 가르킴

      StopWatch stopWatch = new StopWatch();
      stopWatch.start();

      Object proceed = joinPoint.proceed();

      stopWatch.stop();
      logger.info(stopWatch.prettyPrint());


      return proceed;
      }
}

 

 

//참고_ https://youtu.be/3750wh1wNuY?list=PLfI752FpVCS8_5t29DWnsrL9NudvKDAKY

728x90
반응형