순환 참조란 의존성이 있는 두 개 이상의 구성 요소가 서로를 직접 또는 간접적으로 참조하는 상황을 말합니다.
순환참조가 발생하는 경우 호출 시 Call stack이 터져 StackOverFlow가 발생하거나 초기화 과정에서 OutOfMemory가 발생할 수 있습니다.
class A -> class B -> class A┌──->── Bean 'a' defined in file [src/java/A.class]
| └── Bean 'b' defined in file [src/java/B.class]
| └── injection of dependency to bean 'a'
└─────┘
class A -> class B -> class C -> class A┌──->── Bean 'a' defined in file [src/java/A.class]
| └── Bean 'b' defined in file [src/java/B.class]
| └── Bean 'c' defined in file [src/java/C.class]
| └── injection of dependency to bean 'a'
└─────┘
| Spring 버전 | 생성자 주입 | 세터 주입 및 필드 주입 |
|---|---|---|
| Spring Framework 4.x 이하 | 순환 참조 시 예외 발생 | 순환 참조 허용 |
| Spring Framework 5.x / Spring Boot 2.5.x 이하 | 순환 참조 시 예외 발생 | 순환 참조 허용 |
| Spring Framework 5.3.x / Spring Boot 2.6.x 이상 | 순환 참조 시 예외 발생 | 기본적으로 순환 참조 허용 안 함 (명시적으로 허용 설정 가능) |
BeanCurrentlyInCreationException가 발생합니다.BeanCurrentlyInCreationException이 발생합니다.BeanCurrentlyInCreationException이 발생합니다.BeanCurrentlyInCreationException이 발생합니다.spring.main.allow-circular-references 프로퍼티를 true로 설정하여 순환 참조를 명시적으로 허용할 수 있습니다.