AOP

  • 관점 지향 프로그래밍
  • 어떤 로직을 기준으로 핵심적인 관점, 부가적인 관점으로 나누어서 보고 그 관점을 기준으로 각각 모듈화하겠다는 것
    • 모든 메소드의 호출 시간을 측정하려고 할 때
    • 공통 관심 사항(cross-cutting concern) vs 핵심 관심 사항(core concern)
  • AOP가 필요한 상황
long start = System.currentTimeMillis(); 
try{
	validateDuplicateMember(member); 
    memberRepository.save(member); 
    return member.getId(); 
}finally {
    	long finish = System.currentTimeMillis(); 
        long timeMs=finish-start; 
        System.out.println("join = " + timeMs + "ms"); 
}

AOP를 사용하지 않는다면 메소드 호출시간을 측정해주는 것을 포함시켜야한다.

 

시간측정 AOP 등록

@Aspect //이걸 적어야 aop사용가능 
@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 timeMs = finish-start; 
            System.out.println("END: "+joinPoint.toString()+" "+timeMs+"ms"); 
        } 
    } 
}

서비스 하위로 메소드 호출시간을 보고 싶을 때 : `@Around("execution( hello.hellospring.service.(..))")`

  • 회원가입, 회원 조회등 핵심 관심사항과 시간을 측정하는 공통 관심 사항을 분리.
  • 시간을 측정하는 로직을 별도의 공통 로직으로 생성.
  • 핵심 관심 사항 깔끔하게 유지가능.
  • 변경이 필요하면 이 로직만 변경하면 된다.
  • 원하는 적용 대상을 선택가능.

@Component가 아닌 직접 @Bean으로 참조 했을 때

@Configuration 
public class SpringConfig {
	@Bean 
    public TimeTraceAop timeTraceAop() {
    	return new TimeTraceAop(); 
    } 
}
  • 이 상태에서 @Around("execution(* hello.hellospring..*(..))")라고 한다면 자기 자신인 TimeTraceAop를 생성하는 코드인 SpringConfig의 timeTraceAop() 메서드도 AOP로 처리하게 된다. 따라서 순환참조 문제가 발생하게 된다.
  • 다음과 같이 AOP 대상에서 SpringConfig를 빼주면 된다.
  • @Around("execution(* hello.hellospring..*(..)) && !target(hello.hellospring.SpringConfig)")

 

Ctrl+Alt+L : 코드정렬

인프런 '스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술' 통해 학습 중.

+ Recent posts