[Spring Introduction] AOP - 순환 참조 발생이유와 해결

Hyeri·2021년 2월 17일
1

Spring Introduction

목록 보기
4/4
post-thumbnail

-인프런에서 김영한강사님의 스프링 강의를 들으며 정리하는 노트-

AOP를 @Component를 사용해서 스프링 빈에 등록하는 방법 말고
@Bean을 통해 직접 스프링 빈으로 등록했을 때 순환 참조 오류가 발생한다.
그 이유는 무엇이며 어떻게 해결해야 할까?


오류가 발생하는 기존 코드
TimeTraceAop.java

@Aspect
public class TimeTraceAop {
    // 공통 관심사항을 어디세 적용할지 targetting
    @Around("execution(* com.hello.hellospring..*(..))")

    public Object execute(ProceedingJoinPoint joinPoint) throws Throwable{...}
}

SpringConfig.java

@Configuration
public class SpringConfig {

    @Bean
    public TimeTraceAop timeTraceAop() {
        return new TimeTraceAop();
    }
}

TimeTraceAop의 AOP 대상을 지정하는 @Around 코드를 보면, SpringConfig의 timeTraceAop() 메서드도 AOP로 처리하게 된다. 그런데 이게 바로 자기 자신인 TimeTraceAop를 생성하는 코드인 것이다. 그래서 순환 참조 문제가 발생한다.

반면 컴포넌트 스캔을 사용할 때는 AOP의 대상이 되는 이런 코드 자체가 없기 때문에 문제가 발생하지 않는다.

그러면 AOP 설정 클래스를 빈으로 직접 등록할 때는 어떻게 문제를 해결해야 할까?
바로 AOP 대상에서 SpringConfig를 빼주면 된다.


실행되는 코드
TimeTraceAop.java

@Aspect
public class TimeTraceAop {
    
    @Around("execution(* com.hello.hellospring..*(..)) && !target(com.hello.hellospring.SpringConfig)")
//    @Around("execution(* com.hello.hellospring..*(..))")

    public Object execute(ProceedingJoinPoint joinPoint) throws Throwable{...}
}
profile
아무거나 내가 적고 싶은거 🤟

0개의 댓글