오늘은 내가 프로젝트를 진행하면서 마주했던 문제 중 가장 흔한 '순환참조' 문제에 대해 설명해 보겠다.
처음 마주했던 이슈는 다음과 같다.
이슈
👉 Local 환경에서 Spring boot를 실행시켰을때는 분명 멀쩡했는데, Git action으로 CICD를 진행하는 과정에서 다음과 같은 오류가 떴다.
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'commentService' defined in file [/home/runner/work/post-service/post-service/build/classes/java/main/com/justdo/plug/post/domain/comment/service/CommentService.class]: Unsatisfied dependency expressed through constructor parameter 1: Error creating bean with name 'postService' defined in file [/home/runner/work/post-service/post-service/build/classes/java/main/com/justdo/plug/post/domain/post/service/PostService.class]: Unsatisfied dependency expressed through constructor parameter 1: Error creating bean with name 'postHashtagService': Injection of autowired dependencies failed
문제
👉 위 오류 문구를 자세히 보면 결국 Spring boot에서 자주 발생하는 문제 중 하나인 ‘순환 참조 오류’ 였다.
- **CommentService**가 **PostService**를 의존.
- **PostService**가 **postHashtagService**를 의존.
- **postHashtagService**가 다시 **CommentService**를 의존하거나 다른 방식으로 순환 구조를 형성.
일단 그전에 순환 참조란?
Spring Boot에서의 순환 참조는 일반적으로 객체 간의 상호 의존성이나 참조가 루프 형태로 발생하는 경우
보통은 의존성 주입(Dependency Injection)에서의 순환 참조 오류가 일어나는데 예시로 다음과 같다.
- Spring에서는 주로 의존성 주입을 사용하여 객체 간의 관계를 설정. 이 때, A 객체가 B 객체를 의존하고 B 객체가 다시 A 객체를 의존하는 구조가 발생
- 예를 들어, A가 B를 의존하고 B가 다시 A를 의존하는 경우, Spring IoC 컨테이너는 이를 해결할 방법이 없어서 순환 참조가 발생
해결
👉 순환 참조 오류를 해결하는 방법에는 여러가지가 있다.
- 생성자 주입 대신 Setter Injection 사용
- Lazy Initialization 사용
- ApplicationContextAware 인터페이스 사용
하지만 나는 위 3가지 방식 중 굳이 어노테이션이나 새로운 메서드를 사용하지 않고 직접 순환 참조가 아닌
참조의 부모 자식을 확실하게 정해주기로 했다.
- **CommentService**가 **PostService**를 의존.
- **postHashtagService**가 **PostService**를 의존.
- 그리고 postHashtagService와 CommentService는 서로에게 독립적으로 작동하도록 로직을 수정
'Springboot' 카테고리의 다른 글
SpringBoot: TDD(Test-Driven-Development)란? (2) | 2025.01.03 |
---|---|
Spring Batch 활용 (1) | 2024.12.09 |
Spring boot: DDD(Domain Driven Design)란? (0) | 2024.09.23 |
Spring boot 쿼리 최적화 문제와 Spring Cloud Openfeign (1) | 2024.06.19 |
SpringBoot Builder 패턴의 이해 (0) | 2024.04.03 |