<스프링입문>07. AOP

박서연·2023년 3월 30일
0

Spring

목록 보기
7/10

📌 단축키

ctrl+alt+v

📌 AOP가 필요한 상황

🔸 공통 관심 사항(cross-cutting concern) vs 핵심 관심 사항(core concern)
🔸 모든 메소드의 호출 시간을 측정하고 싶을 경우
🔸 문제

  • 회원가입, 회원 조회에 시간을 측정하는 기능은 핵심 관심 사항이 아님
  • 시간을 측정하는 로직은 공통 관심 사항
  • 시간을 측정하는 로직과 핵심 비즈니스의 로직이 섞여서 유지보수가 어려움
  • 시간을 측정하는 로직을 별도의 공통 로직으로 만들기 어려움
  • 시간을 측정하는 로직을 변경할 때 모든 로직을 찾아가면서 변경해야함

📌 AOP 적용

🔸 AOP(Aspect Oriented Programming)
🔸 공통 관심 사항과 핵심 관심 사항 분리

🔸 실제가 아닌 Proxy를 만들어 동작

1. TimeTraceAop.java

main/.../hello.hellospring/aop/TimeTraceAop.java
main/.../hello.hellospring 아래에 aop 이름의 package 생성 후 TimeTraceAop.java 파일 생성

🔸 @Aspect 작성 => AOP로 사용하기 위해
🔸 @Around("execution( hello.hellospring..(..))")
어디에 aop적용할지 => hello.hellospring 아래의 모든 파일에 적용할 것
🔸 execute 함수 생성
public Object execute(ProceedingJoinPoint joinPoint) throws Throwable {}
🔹 System.currentTimeMillis(); 작성 후 단축키 ctrl+alt+v로 변수 생성 후 변수명 start로 변경
🔹 System.out.println("START: "+joinPoint.toString());
🔹 try {} finally {}
🔹 (try 내부)joinPoint.proceed(); 작성 후 단축키 ctrl+alt+v로 변수 생성 후 변수명 result로 변경 + return result; . 이후 단축키 ctrl+alt+n로 inline으로 변경
=> 다음 메소드로 진행
🔹 (finally 내부) System.currentTimeMillis(); 작성 후 단축키 ctrl+alt+v로 변수 생성 후 변수명 finish로 변경
🔹 (finally 내부) long timeMs=finish-start;
🔹 (finally 내부) System.out.println("END: "+joinPoint.toString() + " " + timeMs + "ms");

2. SpringConfig.java

main/.../hello.hellospring/SpringConfig

🔸 스프링 빈 등록
🔸 @Bean
🔸 public TimeTraceAop timeTraceAop() {
return new TimeTraceAop();
}

💡 SpringConfig로 등록하지 않고 TimeTraceAop.java 위에 @Component 작성해 빈 등록할 수도 있음 => 실습에서는 이렇게. But 원래 AOP는 config에 등록하는 것이 보기 좋음

0개의 댓글