Circular dependency xảy ra khi A cần B và B cần A → Spring không biết tạo cái nào trước.
@Service class A { A(B b) {} }
@Service class B { B(A a) {} } // circular!Spring Boot 2.6+ throw exception ngay khi startup:
The dependencies of some of the beans form a cycle:
a → b → aFix (ưu tiên theo thứ tự):
1. Tái cấu trúc — trích logic chung vào class C, A và B đều phụ thuộc C. Giải pháp đúng về kiến trúc.
2. @Lazy — inject lazily, proxy được tạo trước:
A(@Lazy B b) {}3. Setter injection thay constructor — Spring init bean trước, inject sau.
Không nên: spring.main.allow-circular-references=true — suppress warning nhưng giữ nguyên vấn đề kiến trúc.
Circular dependency occurs when A needs B and B needs A → Spring cannot determine which to create first.
@Service class A { A(B b) {} }
@Service class B { B(A a) {} } // circular!Spring Boot 2.6+ throws on startup:
The dependencies of some of the beans form a cycle:
a → b → aFixes (prefer in this order):
1. Refactor — extract shared logic into class C; A and B both depend on C. The architecturally correct solution.
2. @Lazy — inject lazily, a proxy is created first:
A(@Lazy B b) {}3. Setter injection instead of constructor — Spring creates the bean first, injects later.
Avoid: spring.main.allow-circular-references=true — suppresses the error but keeps the architectural problem.