Error creating bean with name 'springSecurityConfig': Requested bean is currently in creation: Is there an unresolvable circular reference?

date
Jul 31, 2022
slug
Error-creating-bean-with-name-springSecurityConfig
status
Published
tags
Bugfix
API
REST
Spring Boot
Spring Security
summary
type
Post

Background

I created the security configuration class to secure my Dog REST API using Basic Authentication:

Problem

When I tried to run my REST API, I got the error below:

What’s wrong

This error was occurring because I in SpringSecurityConfig was trying to use the @Bean for PasswordEncoder in password(), but this @Bean was not yet in the Spring Container/Application Context, which is why the error reported that the @Bean was being created, because in fact when I used @Autowired in configureGlobal, the @Bean for PasswordEncoder has not been placed in the Spring Container/Application Context.
This problem does not occur when using the version 2.1.6-RELEASE of Spring Boot, which allows this to be done as it puts all the @Bean present in a class into the Spring Container/Application Context and then runs @Autowired which ends up using the @Bean present in the Spring Container/Application Context.
but since I was using the version 2.7.1 , this can’t be done because since version 2.2.x+ Spring Boot has a good practice that we can’t put in the same class the @Bean and make the @Autowired of a method or property that will use this @Bean to avoid conflicts.

Solution

There are two simple ways to fix that problem:
  1. Include the property in application.properties:
    1. Create the EncoderConfig class where the @Bean for PasswordEncoder to move

      References

       

      © Foy Wan 2022 - 2025