Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relying upon circular reference is discouraged and they are prohibited, by default, in spring boot application

Tags:

spring-boot

I am getting below error message when I am running my spring boot application.

Description:

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

┌─────┐
|  securityConfiguration (field private com.prity.springbootdemo1.service.UserService com.prity.springbootdemo1.config.SecurityConfiguration.userService)
↑     ↓
|  userServiceImpl (field private org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder com.prity.springbootdemo1.service.UserServiceImpl.passwordEncoder)
└─────┘


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.
like image 799
prity sinha Avatar asked Sep 12 '25 05:09

prity sinha


2 Answers

You can try with this. Add it to file application.properties

spring.main.allow-circular-references=true

And try to run. This is not best solution you still need to find better way to fix problem.

like image 170
Domagoj Ratko Avatar answered Sep 15 '25 02:09

Domagoj Ratko


So if you have a class A and you somehow run into this problem when injecting the class A into the constructor of class B, use the @Lazy annotation in the constructor of class B. This will break the cycle and inject the bean of A lazily into B. So, instead of fully initializing the bean, it will create a proxy to inject into the other bean. The injected bean will only be fully created when it's first needed.

@Component
public class CircularDependencyA {

    private CircularDependencyB circB;

    @Autowired
    public CircularDependencyA(@Lazy CircularDependencyB circB) {
        this.circB = circB;
    }
}
like image 30
Dancan Chibole Avatar answered Sep 15 '25 02:09

Dancan Chibole