@Configuration
@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfig {
private final UserDetailsService userDetailsService;
@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated()
)
.build();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}
while running above code i got error Requested bean is currently in creation: Is there an unresolvable circular reference? using PasswordEncoder Bean why it i got this error how to solve this error.
>Solution :
The circular dependency occurs as follows:
- The
SecurityConfigclass has a dependency on theUserDetailsServicebean, which is likely provided by Spring Security. - The
UserDetailsServicebean requires thePasswordEncoderbean to encode and decode passwords for authentication. - The
PasswordEncoderbean, in turn, depends on theSecurityConfigclass to create theAuthenticationManager.
This creates a cycle in the dependency graph, leading to the circular reference error.
To solve this error, you can break the circular dependency by making some changes to the code:
-
Move the
PasswordEncoderbean creation to a separate@Configurationclass. This way, it won’t be involved in the circular reference.@Configuration
public class PasswordEncoderConfig {
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
} -
Remove the
@Autowiredannotation from theconfigureGlobalmethod in theSecurityConfigclass. Spring will automatically inject theUserDetailsServiceinto theAuthenticationManagerBuilderwithout the need for explicit@Autowired.@Configuration
@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfig {private final UserDetailsService userDetailsService; // ... (other methods) public void configureGlobal(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } // ... (other methods)}
By separating the PasswordEncoder bean into its configuration class and removing the @Autowired from the configureGlobal method, you should be able to resolve the circular dependency issue and avoid the "Requested bean is currently in creation" error. Remember to check other parts of your codebase to ensure there are no other circular dependencies that could lead to similar issues.