What is a circular dependency issue?

A circular dependency occurs when two or more Spring beans depend on each other directly or indirectly during object creation. Because each bean requires the other to be instantiated first, Spring cannot complete the dependency injection process, which may result in application startup failure.

Key Points: • Circular dependencies create a dependency cycle between beans, making bean creation difficult. • Constructor-based circular dependencies typically fail during application startup. • The best solution is to redesign the application and reduce tight coupling between components.

Example:

Direct Circular Dependency:

Bean A → Depends on Bean B

Bean B → Depends on Bean A

Spring cannot determine which bean should be created first.

Indirect Circular Dependency:

Bean A → Bean B

Bean B → Bean C

Bean C → Bean A

This also creates a dependency cycle.

Code Example:

@Service
public class OrderService {

    private final PaymentService paymentService;

    public OrderService(
            PaymentService paymentService) {

        this.paymentService =
                paymentService;
    }
}

@Service
public class PaymentService {

    private final OrderService orderService;

    public PaymentService(
            OrderService orderService) {

        this.orderService =
                orderService;
    }
}

Result:

BeanCreationException: Circular reference involving OrderService and PaymentService

How to Resolve It:

• Redesign the application to remove tight coupling. • Use @Lazy to delay bean initialization. • Use setter injection in specific cases. • Use ObjectProvider for lazy bean access. • Apply event-driven communication between services.

Real-World Example:

In an e-commerce application:

• OrderService calls PaymentService. • PaymentService calls OrderService.

This creates a circular dependency.

A better design is:

• OrderService → PaymentService • PaymentService → TransactionService

This removes the dependency cycle completely.

Best Practice: Avoid circular dependencies whenever possible. If they appear, they often indicate a design issue and can usually be eliminated through proper separation of responsibilities.

Interview Tip: A concise interview answer is: A circular dependency occurs when two or more Spring beans depend on each other for creation. For example, Bean A depends on Bean B and Bean B depends on Bean A. This can prevent Spring from creating the beans, especially when using constructor injection. The preferred solution is to redesign the application to remove the dependency cycle, although @Lazy and setter injection can be used as temporary fixes.