AOP : Aspect Oriented Programming

공통 관심사항 , 핵심 관심사항 분리하는 것!

 

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%EC%9E%85%EB%AC%B8-%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8/lecture/49601?tab=note&speed=0.75

 

모든 메서드에 시간 측정 로직을 붙이는 것이아니라

한 곳에 모으고 적용하는것이다!

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;

@Component
@Aspect
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 timeMs = finish - start;
            System.out.println("END: " + joinPoint.toString() + " " + timeMs + "ms");
        }
    }
}

TimeTraceAop 클래스를 생성한다! 

AOP는 @Aspect를 해줘야한다.

그리고 스프링 빈으로 등록해야한다.

 

@Component 를 쓰거나 SpringBean에 등록을 해서 쓸 수 있다.

나는 @Component를 써서 진행하였다!

 

한가지를 더해주어야하는데

@Around 라는 것으로 공통 관심 사항을 어디에 적용할 건지

타게팅을 해줄 수 있다 따로 문법이 있다! 매뉴얼 대로 하면 

쓰기 쉬웠다!

 

콘솔에 찍힌 문구이다.

START: execution(String hello.hellospring.controller.HomeController.home())
END: execution(String hello.hellospring.controller.HomeController.home()) 7ms
START: execution(String hello.hellospring.controller.MemberController.list(Model))
START: execution(List hello.hellospring.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()) 192ms
END: execution(List hello.hellospring.service.MemberService.findMembers()) 204ms
END: execution(String hello.hellospring.controller.MemberController.list(Model)) 230ms

 

 

 

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%EC%9E%85%EB%AC%B8-%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8/lecture/49601?tab=note&speed=0.75

 

스프링의 AOP 동작 방식 

 

AOP를 적용 하면 가짜 멤버 서비스를 만들어낸다(프록시)

가짜 스프링빈이 끝나면 그때 진짜를 호출해준다.

컨트롤러가 호출하는 것은 프록시라는 가짜 서비스를 호출한다.

 

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%EC%9E%85%EB%AC%B8-%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8/lecture/49601?tab=note&speed=0.75

AOP 적용 전 후 비교그림이다.

 

MemberController에서 

MemberService.getClass()로 콘솔에 찍어보면

 

memberService = class hello.hellospring.service.MemberService$$EnhancerBySpringCGLIB$$8c469d23

 

실제가 아닌 가짜를 확인할 수 있었다!!

 

이 모든 것이 DI를 통해 이루어지기 때문에 가능한 일이다.

 

'웹프로그래밍 > Spring 입문' 카테고리의 다른 글

21. AOP  (0) 2021.07.01
20. 스프링 데이터 JPA  (0) 2021.06.30
19. JPA  (0) 2021.06.30
18. 스프링 JDBC Template  (0) 2021.06.29
17. 스프링 통합 테스트  (0) 2021.06.29

+ Recent posts