The dependencies of some of the beans in the application context form a cycle

김재민·2022년 4월 26일
0
post-thumbnail

스프링 JPA 프로젝트를 진행하던 도중

before ) static클래스에서

@Component
@RequiredArgsConstructor
public class InitDb {

	private final InitService initService;
    
	static class InitService {
	}
}

after ) private클래스로 변경

@Component
@RequiredArgsConstructor
public class InitDb {

	private final InitService initService;

	private class InitService {
	}
}

내부 static클래스가 정의되어있는 부분에서 static을 지우고 private으로 전환하고 동작을 했을 때

The dependencies of some of the beans in the application context form a cycle:

┌─────┐
|  initDb defined in file [C:\Users\Hansol\OneDrive\Desktop\study\hello-spring\SpringBase\build\classes\java\main\hello\hellospring\service\InitDb.class]
↑     ↓
|  hello.hellospring.service.InitDb$InitService
└─────┘

다음과 같은 에러가 발생하였다.
찾아보니 스프링 순환 종속성 에러라고 하였다.

순환 종속성 에러에 대한 설명으로는
-> 둘 이상의 Bean이 생성자를 통해 서로 주입하려고할 때 발생한다고 한다.
( A클래스가 B클래스의 Bean을 주입받고, B클래스가 A클래스의 Bean을 주입받는 상황처럼 서로 순환되어 참조할 경우 발생하는 문제를 의미)

문제

그렇다면 이 문제에 대한 직관적인 설명을 김영한님께서 해주셨다.

자바의 내부 클래스 (inner class)는 static inner class가 아니라면 내부 클래스를 포함하고 있는 외부 클래스의 객체가 필요합니다.

initDb를 생성하려는데 initDb는 InitService를 멤버변수로 가지고 있으므로 InitService를 생성해서 주입해야 합니다. 그래서 InitService를 생성하려고 하는데 InitService가 내부 클래스라서 InitService를 포함하고 있는 외부 클래스(InitDb)의 객체를 생성하려고 합니다.

이 과정에서 순환이 생기게 됩니다.

static inner class는 자신을 감싸고 있는 외부 클래스의 객체를 필요로 하지 않습니다.
따라서 InitService를 static inner class로 선언하여 사용

profile
어제의 나보다 나은 오늘의 내가 되자!🧗‍♂️

0개의 댓글