Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is a Circular Dependency in Spring and how do you resolve it? स्प्रिंग में सर्कुलर डिपेंडेंसी क्या है और इसे कैसे हल करें?

Answer

A circular dependency occurs when Bean A depends on Bean B, and Bean B depends back on Bean A (directly or through a longer chain), creating a cycle the container can't resolve through straightforward constructor injection since neither bean can be fully constructed first.

With constructor injection, Spring throws a BeanCurrentlyInCreationException at startup, surfacing the design problem immediately. Common fixes include refactoring to remove the cycle (usually the correct fix — it often signals a design smell), switching one side to setter/field injection so Spring can inject after both beans partially exist, or using @Lazy on one of the dependencies so it's only resolved on first use rather than at construction time.

@Service
public class ServiceA {
    private final ServiceB serviceB;
    public ServiceA(@Lazy ServiceB serviceB) { this.serviceB = serviceB; }
}

सर्कुलर डिपेंडेंसी तब होती है जब बीन A, बीन B पर निर्भर करता है, और बीन B वापस बीन A पर निर्भर करता है, जिससे एक चक्र बनता है जिसे कंटेनर सीधे कंस्ट्रक्टर इंजेक्शन से हल नहीं कर सकता।

कंस्ट्रक्टर इंजेक्शन के साथ, स्प्रिंग स्टार्टअप पर BeanCurrentlyInCreationException फेंकता है। सामान्य समाधानों में चक्र को हटाने के लिए रीफैक्टर करना (आमतौर पर सही समाधान), एक तरफ को सेटर/फील्ड इंजेक्शन में बदलना, या एक डिपेंडेंसी पर @Lazy उपयोग करना शामिल है।

@Service
public class ServiceA {
    private final ServiceB serviceB;
    public ServiceA(@Lazy ServiceB serviceB) { this.serviceB = serviceB; }
}

Was this answer clear?