[Spring] Error - The dependencies of some of the beans in the application context form a cycle

하쮸·2025년 11월 11일

Error, Why, What, How

목록 보기
52/68

1. 현재 상황.

Description:

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

┌─────┐
|  securityConfig defined in file [C:\Java\...\config\SecurityConfig.class]
↑     ↓
|  customOauth2UserService defined in file [C:\Java\...\security\CustomOauth2UserService.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.


Process finished with exit code 1
  • securityConfig에서 customOauth2UserService를 주입 받고 있는데
    customOauth2UserService에서도 securityConfig or securityConfig에서 생성된 빈(Bean)을 주입 받고 있기 때문에 순환 참조(circular dependency) 오류가 발생하였음.
    • securityConfig에서는 oauth2Login을 위해 customOauth2UserService가 필요.
    • customOauth2UserService에서는 사용자의 비밀번호를 암호화 하기 위해서 securityConfig 내부에 정의되어 있는 (@Bean)PasswordEncoder가 필요함.
  • 즉, 현재 securityConfig customOauth2UserService 이런 상황임.

2. 해결.

  • securityConfig 내부에 있는 (@Bean)PasswordEncoder을 외부로 분리시켜야함.
    • 즉, 별도의 독립적인 클래스 파일에 정의하면됨.
@Configuration
public class PasswordConfig {
    // PasswordEncoder 빈 등록. (BCryptPasswordEncoder : PasswordEncoder 구현체)
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
  • 이렇게 하면 CustomOauth2UserService는 이제 SecurityConfig에 의존하지 않고 스프링 컨텍스트의 독립적인 빈(Bean)인 PasswordEncoder를 주입받아 사용할 수 있음.

3. 참고.

profile
Every cloud has a silver lining.

0개의 댓글