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

반응형

The dependencies of some of the beans in the application context form a cycle 양방향 의존관계 오류

스프링 프레임워크에서는 @Autowire 어노테이션을 이용해서 의존성 주입을 한다. 그런데 서로 다른 두 개의 클래스에서 서로를 의존성 주입하면 위와 같이 양방향 의존관계 오류가 발생한다.

위 이미지에서는 userService, reservationService 클래스가 서로를 의존성 주입하고 있어 오류가 발생했다. 이는 A를 변경하면 B가 영향을 받고, B를 변경하면 A가 영향을 받으므로 나쁜 설계라고 할 수 있다. 

이를 해결하기 위해 A>B, B>A 의존 관계가 있다면 새로운 C를 만들어서 A>B>C로 의존관계를 갖도록 변경하여 문제를 해결 할 수 있다.

출처

//www.inflearn.com/questions/83328

반응형

'스프링 > 스프링' 카테고리의 다른 글

[F-lab] 12주차 정리 - 프로젝트 개발 2주차  (0) [MyBatis] 오류 해결: org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.executor.ExecutorException: No constructor found in XXX  (0) [Spring] The dependencies of some of the beans in the application context form a cycle 양방향 의존관계 오류  (0) [Spring] @Scheduled - 스프링에서 주기적인 작업을 진행하는 법  (0) [Spring] 오류 해결: org.hibernate.AnnotationException: No identifier specified for entity  (0) [Junit5] 스프링4에서 Junit5의 @ExtendWith(SpringExtension.class) 코드 사용하기  (0)
2021.11.08
2021.08.20
2021.08.09
2021.05.21
2021.04.15
2021.04.07

들어가며

스프링에서 프로젝트를 진행하면 종종 빈 순환 참조가 발생하는데, 이에 대한 해결책을 알아보자. 들어가기에 앞서, 빈 순환 참조는 생성자를 통해서 빈을 주입했을 때, Bean A -> Bean B -> Bean A … 계속해서 순환 참조하는 것을 말한다.

1. 빈 순환 참조가 발생하는 상황

@Component public class CircularA { private CircularB circularB; public CircularA(CircularB circularB) { this.circularB = circularB; } }

@Component public class CircularB { private CircularA circularA; public CircularB(CircularA circularA) { this.circularA = circularA; } }

각각 @Component를 통해서 빈으로 등록시킨다. 상대방 빈을 생성자를 통해서 주입받는다. CircularA 컴포넌트는 빈으로 등록될 때CircularB를 참조하고 있고, CircularB 컴포넌트도 빈으로 등록할 때 Circular A를 참조한다.

@SpringBootTest @RunWith(SpringRunner.class) public class CircularTest { @Test public void test() { // just spring context load } }

애플리케이션을 띄우거나, 아무것도 작성되지 않은 테스트 케이스를 돌리게되면 다음과 같은 예외가 발생한다.

************************** APPLICATION FAILED TO START *************************** Description: The dependencies of some of the beans in the application context form a cycle: ┌─────┐ | circularA defined in file [/Users/andrew/workspace/spring-boot-practice/target/classes/com/example/demo/spring/circular/CircularA.class] ↑ ↓ | circularB defined in file [/Users/andrew/workspace/spring-boot-practice/target/classes/com/example/demo/spring/circular/CircularB.class] └─────┘

순환참조가 발생했고, 어떤 빈에서 순환 참조가 일어나는지 알려준다.

2. 해결 방법 1. @Lazy

여러 가지 해결 방법이 있지만, 기본적인 원리는 서로 빈이 생성되는 시기를 늦추거나 조율해서 동시에 참조하는게 아니라, 하나의 빈이 생성이 완료 된 후, 동작을 하게끔 만들어 주는게 키포인트!

@Component public class CircularA { private CircularB circularB; public CircularA(@Lazy CircularB circularB) { this.circularB = circularB; } }

사실 여러 개의 블로그를 봤지만, 결국 빈 순환 참조가 난다는 것은 모델링 설계가 잘못되었음을 알려주는 것이라고 했다. 그렇기 때문에 위에 방법들은 궁극적인 해결책 보다는 가벼운 임시 조치! 아니면 @Autowired, @Inject 어노테이션을 사용하는 것 뿐

📚 Related Posts

  • SpringBoot, MongoDB 시작하기 Aug 18, 2021
  • Spring Boot 서버 타임존 설정 방법 Aug 10, 2021
  • SpringBoot CommandLineRunner, ApplicationRunner 초기화 방법 Aug 6, 2021
  • Jackson, LocalDateTime Serialization, Deserialization 이슈 Jul 24, 2021
  • Spring Boot, Dockerfile로 이미지 생성, 배포하기 Jul 11, 2021
  • SpringBoot RabbitMQ 연동하기 Nov 25, 2020
  • Junit5 정리 May 16, 2020
  • Spring Sentry(에러 트래킹 서비스) 적용하기 May 12, 2020
  • [Spring] 빈 주입하는 방법 && Best Practice May 5, 2020
  • Thymeleaf 실무에서 자주 사용하는 것들 Jan 19, 2020
  • Thymeleaf Collection 정보 화면에 렌더링하기 Jan 19, 2020
  • Spring, JPA를 이용한 REST API 만들기 Jan 18, 2020
  • [Spring] MultipartFile을 이용한 파일 업로드 Jan 2, 2020
  • [Spring] 모델 검증(validation) Dec 12, 2019
  • [Spring]HandlerMethodArgumentResolver 인터페이스 Jul 25, 2019
  • [Spring] DispatcherServlet에 대해서 알아보자 Apr 21, 2019
  • [Spring] MVC 만들어 보기 Apr 17, 2019
  • [Spring] 메세지 컨버터 Apr 13, 2019
  • [Spring] MVC 살펴보기 Apr 13, 2019
  • [Spring] @ConfigurationProperties를 이용해서 properties값들을 클래스로 관리하기 Apr 13, 2019
  • [Spring] Profile 설정하기 Apr 13, 2019
  • [Spring] SpringApplication를 통한 코딩 Apr 12, 2019
  • [Spring Boot] 스프링 부트 3가지 특징 Apr 12, 2019
  • [Spring] @SpringBootAppllication 어노테이션에 대한 고찰 Apr 12, 2019
  • [Spring] bean circular dependencies (빈 순환 참조) Apr 12, 2019
  • [Spring]Bean에 대해서 알아보자 Apr 12, 2019
  • SpringBoot, JPA, H2를 이용한 간단한API 작성 Apr 12, 2019
  • [Spring] Spring Data Common 프로젝트 살펴보기 Apr 12, 2019

What is bean dependency in Spring?

Advertisements. In Spring Boot, we can use Spring Framework to define our beans and their dependency injection. The @ComponentScan annotation is used to find beans and the corresponding injected with @Autowired annotation.

What is cyclic dependency in Spring?

What Is a Circular Dependency? A circular dependency occurs when a bean A depends on another bean B, and the bean B depends on bean A as well: Bean A → Bean B → Bean A. Of course, we could have more beans implied: Bean A → Bean B → Bean C → Bean D → Bean E → Bean A.

What is cyclic dependency in Java?

A circular or cyclic dependency is a situation where two or more independent modules or components rely on each other to function properly. This is referred to as mutual recursion. Circular dependency generally occurs in a modular framework while defining a dependency between modules or components.

How do you fix cyclic dependency?

There are a couple of options to get rid of circular dependencies. For a longer chain, A -> B -> C -> D -> A , if one of the references is removed (for instance, the D -> A reference), the cyclic reference pattern is broken, as well. For simpler patterns, such as A -> B -> A , refactoring may be necessary.

zusammenhängende Posts

Toplist

Neuester Beitrag

Stichworte