Bean Currently In Creation Exception: unresolvable circular reference error after upgrading Spring Boot to 2.6

Tech Insights

If you have just upgraded to Spring Boot version 2.6 you are likely to get the following error after deploying the application:

org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name ‘webSecurityConfig’: Requested bean is currently in creation: Is there an unresolvable circular reference?

How to solve the BeanCurrentlyInCreationException?

Check if you have any @Autowired method calling a @Bean like PasswordEncoder. If yes, that’s the root cause of the issue. Just change the method’s name to configure and also the @Autowired annotation to @Override. With this, you should be able to deploy the application without the BeanCurrentlyInCreationException occuring again.

To be more clear, check the following code snippets:

Code before the fix:

@Autowired
public void configUser(AuthenticationManagerBuilder auth) throws Exception {
	 auth.jdbcAuthentication().dataSource(dataSource)
	  .passwordEncoder(passwordEncoder())
	  .usersByUsernameQuery(
	   "select email, password, enabled from user where email=? AND enabled=true")
	  .authoritiesByUsernameQuery(
	   "select u.email, r.role_name from user u join role r on u.role_id = r.id where u.email=?");
}

Code after the fix:

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
	 auth.jdbcAuthentication().dataSource(dataSource)
	  .passwordEncoder(passwordEncoder())
	  .usersByUsernameQuery(
	   "select email, password, enabled from user where email=? AND enabled=true")
	  .authoritiesByUsernameQuery(
	   "select u.email, r.role_name from user u join role r on u.role_id = r.id where u.email=?");
}

As mentioned in the Spring Boot 2.6 Release Notes, circular references between beans are now prohibited by default. If you are unable to make the above configuration changes in your application to break the dependency cycle, just restore Spring Boot 2.5’s behaviour and automatically attempt to break the dependency cycle. This can be achieved by setting spring.main.allow-circular-references to true, or using the new setter methods on SpringApplication and SpringApplicationBuilder.