AOP가 필요한 상황
- 모든 메소드의 호출 시간을 측정하고 싶다면?
- 공통 관심 사항(cross-cutting concern) vs 핵심 관심 사항(core concern)
- 회원 가입 시간, 회원 조회 시간을 측정하고 싶다면?
언제 어떻게 사용하지만 알면 쉽게 잘 할 수 있다.
- 모든 메소드의 호출 시간을 측정 할 때
우리를 예로 들자면 회원가입을 할 때 시간을 측정 해봐야 합니다.
public Long join(Member member){
long start = System.currentTimeMillis();
try{
//같은 이름이 있는 중복 회원 X
validateDuplicateMember(member);
memberRepository.save(member);
return member.getId();
} finally {
long finish = System.currentTimeMillis();
long timeMs = finish - start;
System.out.println("join = " + timeMs+ "ms");
}
}
만약 1000개가 넘는 메소드에 일일이 적용을 할려고 하면 엄청난 고생을 할 것이다. 이러한 문제들을 해결 하기 위한게 AOP이다.
AOP 적용
- AOP : Aspect Oriented Programming
- 공통 관심 사항(cross-cutting concern) vs 핵심 관심 사항 (core concern) 분리
AOP의 아이디어는 만들어두고 원하는 곳에 적용을 하면 된다.
hellohellospring 에 파일을 하나 만들어서
aop를 만든다.
package hello.hellospring.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 TimerTraceAop {
@Around("execution(* hello.hellospring..*(..))")
public Object execute(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
System.out.println("START: " + joinPoint.toShortString());
try{
return joinPoint.proceed();
}finally {
long finish = System.currentTimeMillis();
long timeMs = finish - start;
System.out.println("END: "+ joinPoint.toString() +" "+ timeMs + "ms");
}
}
}
원래는 Bean으로 만들어도 되는데 이번에는 컴포넌트 스캔을 이용해봤습니다.
그 다음 서버을 실행 시키면
이러면 어디서 밀리고 ,병목이 있는지 알 수 있다. 이러한 기술이 AOP이다.
위에서 썼던 코드는 try,finally 등을 사용해서 핵심 코드들이 더럽게 보였는데 AOP를 쓰게 되면 더욱 간단하게 코드를 확인 할 수 있다.
만약 Service 밑에 있는 애들을 확인하고 싶은면
*@Around*("execution(* hello.hellospring.service..*(..))") 이렇게 작성 하면 된다.
가짜 멤버 서비스를 사용 하는 것 이다.
'Programming > Spring' 카테고리의 다른 글
[Project] Builder 패턴 사용 (0) | 2024.08.21 |
---|---|
Spring Boot JPA를 이용한 수정하기 PUT (0) | 2024.01.08 |
스프링 DB 접근 기술 #7.3~#7.6 (0) | 2023.01.14 |
스프링 DB 접근 기술 #7.1~#7.3 (0) | 2023.01.14 |
회원 관리 예제 - 웹 MVC 개발 #6.1~#6.3 (0) | 2023.01.12 |