JAVA/오류해결

[SpringBoot][오류해결] The dependencies of some of the beans in the application context form a cycle

gakko 2022. 2. 26. 18:00

 

구글 OAuth를 사용하던 도중 오류가 발생했다. 

APPLICATION FAILED TO START. 앱이 실행하는 것에 실패했다고 나온다. 오류 내용을 확인해보자.

 

 

- 오류 내용

***************************
APPLICATION FAILED TO START
***************************

Description: 

The dependencies of some of the beans in the application context form a cycle: 
┌─────┐ 
| securityConfig (field private com.cos.security1.config.oauth.PrincipalOauth2UserService com.cos.security1.config.SecurityConfig.principalOauth2UserService) 
↑    ↓ 
| principalOauth2UserService (field private org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder com.cos.security1.config.oauth.PrincipalOauth2UserService.bCryptPasswordEncoder) 
└─────┘ 

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이 생성자를 통해 서로를 주입되도록 구성하면 Spring IoC 컨테이너에서 감지하는 문제이다.

Description에 나온 화살표도 표시된 그림을 보면 대충 알 수 있는데, 순환참조의 오류가 발생하여 securityConfig와 principalOauth2UserService가 서로를 참조하고 있어 어떤 객체를 먼저 생성할지 문제가 발생한 것이다.

 

 

 

오류 코드

@Service
public class PrincipalOauth2UserService extends DefaultOAuth2UserService {
	
    // 문제의 코드 - 제거해주면 해결
	@Autowired
	private BCryptPasswordEncoder bCryptPasswordEncoder;
	
    ...
}

 

public class SecurityConfig extends WebSecurityConfigurerAdapter{

	@Autowired
	private PrincipalOauth2UserService principalOauth2UserService; 
	
	@Bean
	public BCryptPasswordEncoder encodePwd() {
		return new BCryptPasswordEncoder();
	}
}

SecurityConfig는 PrincipalOauth2UserService 자체를 참조하고, PrincipalOauth2UserService는 SecurityConfig에 있는BCryptPasswordEncoder 클래스를 참조하고 있다. 이것이 순환참조의 원인이다. 굳이 필요없는 클래스라서 제거해줬다.

BCryptPasswordEncoder가 굳이 필요하지 않았기에 제거해주면 오류가 해결된다.