1. Preface

SpringBoot 2.6.x does not recommend the use of circular dependencies, which is good news, SpringBoot is gradually guiding developers to write standard code from the bottom up, but also sad news, circular dependencies are too widely used.

If you upgrade from a low version to 2.6.x, then the first problem you are likely to encounter is a circular dependency problem.

2. Problem recovery

2.1. Code description

The following style of code is more common: both classes have the need to call each other’s methods, so it is easy to write a circular reference.

1
2
3
4
5
6
@Service
public class TbDeptServiceImpl extends ServiceImpl<TbDeptMapper, TbDept> implements ITbDeptService {
    
    @Autowired
    private ITbStaffService staffService;
}
1
2
3
4
5
@Service
public class TbStaffServiceImpl extends ServiceImpl<TbStaffMapper, TbStaff> implements ITbStaffService {
    @Autowired
    private ITbDeptService deptService;
}

2.2. error example

1
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.
1
Despite circular references being allowed, the dependency cycle between beans could not be broken. Update your application to remove the dependency cycle.

2. Problem solving

The simplest way is to allow circular references in the global configuration file, the default value of this property is false, display the declaration as true, you can avoid the project startup console circular reference exception.

1
2
3
spring:
  main:
    allow-circular-references: true

Spring officially forbids the use of circular dependencies by default, although there is an optional configuration that allows developers to continue using circular dependencies.

The official intent of Spring is not to allow developers to write code with circular dependencies, which means that some future version may force them not to use circular dependencies, so gradually eliminating them in new projects is a problem that has to be faced.

Referece https://www.cnblogs.com/javazhishitupu/p/15925762.html