Development/Spring
AOP (Aspect Oriented Programming) 관점 지향 프로그래밍
우봉수
2023. 3. 11. 16:04
AOP 예시 코드
package aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class TimeTraceAop {
@Around("execution(* hello.hellospring..*(..))")
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 timesMs = finish - start;
System.out.println("END: "+joinPoint.toString()+" "+timesMs+"ms");
}
}
}
- 각각의 메소드에 따로따로 구현하지 않더라도 모든 메소드들의 시간 측정 가능
AOP가 필요한 상황
- 모든 메소드의 호출 시간을 측정하고 싶다면?
- 공통 관심사항(시간 측정)과 핵심 관심(기능)사항이 섞여서 유지보수가 힘들어짐
- 공통 관심사항(cross-cutting concern)과 핵심 관심사항(core concern)이 합쳐진 상황을 분리시키고 싶을 때
AOP 사용되는 이유
- 공통 관심사항(cross-cutting concern)과 핵심 관심사항(core concern)을 분리하고 원하는 순간에 적용하기 위해서
- 공통 관심사항을 따로 만들고 Bean에 등록하는 것 으로 중복된 코드들을 방지 할 수 있음
실제 동작 과정
- 스프링 컨테이너에서 검사할 항목에 가짜 Spring bean을 생성(프록시) 후 호출