김영한님의 스프링 입문 강의 학습 내용입니다.
AOP
Why?
- 시간 측정 로직은 공통 관심 사항이다.
- 시간 측정 로직 유지보수가 어렵다.
- 시간 측정 로직을 별도 공통 로직으로 만들기 어렵다.
- 변경 시 모든 로직을 찾아 변경해야한다.
TimeTraceAop
@Component 사용없이 Bean 등록할 때
@Bean
public TimeTraceAop timeTraceAop(){
return new TimeTraceAop();
}
@Aspect
@Component
public class TimeTraceAop {
@Around("execution(* com.example.hellohello..*(..))")
public Object execute(ProceedingJoinPoint joinPoint) throws Throwable{
long start = System.currentTimeMillis();
System.out.println("START: " + joinPoint.toString());
try {
return joinPoint.proceed();
} finally{
long finish = System.currentTimeMillis();
long timeMs = finish - start;
System.out.println("END: " + joinPoint.toString() + " " + timeMs + "ms");
}
}
}
- @Aspect : AOP로 사용가능
- @Around() : 공통 관심 사항을 적용할 위치를 타겟팅
- joinPoint.proceed(); : 다음 메서드로 진행
결과
START: execution(String com.example.hellohello.controller.MemberController.list(Model))
START: execution(List com.example.hellohello.service.MemberService.findMembers())
START: execution(List org.springframework.data.jpa.repository.JpaRepository.findAll())
Hibernate: select member0_.id as id1_0_, member0_.name as name2_0_ from member member0_
END: execution(List org.springframework.data.jpa.repository.JpaRepository.findAll()) 186ms
END: execution(List com.example.hellohello.service.MemberService.findMembers()) 192ms
END: execution(String com.example.hellohello.controller.MemberController.list(Model)) 209ms