순환 의존성 문제

황상익·2024년 8월 8일

Description:

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

┌──->──┐
| transactionRepositoryImpl defined in file [C:\Users\hwang\IdeaProjects\새 폴더\새 폴더\fintech\fintech\out\production\classes\miniproject\fintech\repository\transactionrepository\TransactionRepositoryImpl.class]
└──<-──┘

Action:

Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.

순환 의존성 문제가 발생했다.
두 개 이상의 빈이 서로 필요로 하면서 서로의 생성이 완료되기를 기다리는 상황에서 발생.

  1. 순환 의존성 문제 해셜

1) 설계 변경:
순환 의존성을 피하기 위해 클래스의 의존성을 재구성할 수 있습니다. 예를 들어, 의존성을 단방향으로 만들어 서로가 직접 의존하지 않도록 합니다.

2) @Lazy 어노테이션 사용:
@Lazy 어노테이션을 사용하여 지연 초기화(lazy initialization)를 적용하면 순환 의존성 문제를 해결할 수 있습니다. 이 어노테이션을 사용하면 빈이 실제로 필요할 때까지 생성되지 않습니다.

나는 Lazy 어노테이션을 TransactionRepositoryImpl에 추가해 보았다.

 public TransactionRepositoryImpl(@Lazy TransactionRepository repository) {
        this.repository = repository;
    }

Service 부분에도!

    public TransactionService(@Lazy TransactionRepository transactionRepository,
                              @Lazy AccountService accountService,
                              @Lazy MemoryMemberService memberService,
                              @Lazy MemberDiscountService discountService) {
        this.transactionRepository = transactionRepository;
        this.accountService = accountService;
        this.memberService = memberService;
        this.discountService = discountService;
    }

다만 코드가 지저분해져서 더 나은 방법이 있는지 확이해봐야 겠다...

의존성 부분을 재구성 해봐야 할지도 모르겠다...

profile
개발자를 향해 가는 중입니다~! 항상 겸손

0개의 댓글