Post

순환참조의 오류

순환참조의 오류

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

서버를 가동시키면서 여태 못봤던 오류가 로그에 출력이 되었다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Description:

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

┌─────┐
|  customSecurityConfig defined in file [C:\lee data\java spring\step5.5\practice1\out\production\classes\com\example\test\config\CustomSecurityConfig.class]
↑     ↓
|  customUserDetailsService defined in file [C:\lee data\java spring\step5.5\practice1\out\production\classes\com\example\test\service\security\CustomUserDetailsService.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.

이 오류가 나타난 경위가 단순했는데 둘 이상의 Bean이 생성자를 통해 서로를 주입되도록 시도하면 위와 같은 순환 참조 오류 또는 순환 종속성이라는 문제가 나타난다.

Description에 나온 화살표로 볼 수 있다시피, CustomSecurityConfigCustomUserDetailsService가 서로를 참조하고 있어 어떤 객체를 먼저 생성할지 문제가 발생한 것이다.


해결 방법

  • CustomSecurityConfig
1
2
3
4
5
6
7
8
9
10
11
12
13
@Configuration
@Log4j2
@RequiredArgsConstructor
@EnableMethodSecurity
public class CustomSecurityConfig {

    private final DataSource dataSource;
    private final CustomUserDetailsService userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
  • CustomUserDetailsService
1
2
3
4
5
6
7
@Service
@Log4j2
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

    private final MemberRepository memberRepository;
    private final PasswordEncoder passwordEncoder; //삭제할 부분

CustomSecurityConfigCustomUserDetailsService 자체를 참조하고, CustomUserDetailsServiceCustomSecurityConfig에 있는BCryptPasswordEncoder 클래스를 참조하고 있다.
그래서 CustomUserDetailsService에 있는 passwordEncoder변수를 제거하고 서버를 다시 실행한 결과 정상적으로 서버가 실행되었다.


잡담

여기서 글을 쓰기 시작할 때 독한 마음으로 열심히 달리겠다고 다짐했건만 어느 순간 자신이 지친다고 생각하여 개발공부나 글쓰는 것도 설렁설렁하게 되어 지금 글을 쓰는 주기도 한달 간격이 되고 말았다.
그리고 오늘 다시 마음을 다잡고 달리겠지만 다시 마음이 헤이해질 것이니 스스로 이 말을 내 가슴과 여기에 새겨놓고 계속 생각하자.
“나의 인생 누구도 책임져주지 않고 이러한 열정과 노력을 할 수 있는 시간은 이제 얼마 남지 않았다.”
다시 열심히 해보자


This post is licensed under CC BY 4.0 by the author.