Java Spring Boot: Circular Dependency guide with @Autowired and Constructor Injection
Hey everyone, I'm running into an issue that's driving me crazy... I'm maintaining legacy code that I've looked through the documentation and I'm still confused about Hey everyone, I'm running into an issue that's driving me crazy. I'm sure I'm missing something obvious here, but I'm working with a `BeanCurrentlyInCreationException` when trying to run my Spring Boot application that has two services, `UserService` and `OrderService`, which are circularly dependent on each other... When I attempt to start the application, I see the following behavior message: ``` behavior creating bean with name 'userService': behavior creating bean with name 'orderService': Bean currently in creation: Is there an unresolvable circular reference? ``` Both services are annotated with `@Service`, and I'm using constructor injection. Here's a simplified version of my code: ```java @Service public class UserService { private final OrderService orderService; @Autowired public UserService(OrderService orderService) { this.orderService = orderService; } public void processOrder() { orderService.createOrder(); } } @Service public class OrderService { private final UserService userService; @Autowired public OrderService(UserService userService) { this.userService = userService; } public void createOrder() { // Order creation logic } } ``` I've tried breaking the dependency by introducing a third service, but that doesn't seem to resolve the circular reference. I also read that using `@Lazy` can help in resolving such issues, so I tried adding `@Lazy` to one of the services but it still results in the same behavior. I would appreciate any guidance on how to resolve this circular dependency scenario effectively without compromising the design principles of my application. This is part of a larger CLI tool I'm building. I'm coming from a different tech stack and learning Java. For reference, this is a production service. Could this be a known issue? This is part of a larger REST API I'm building. Cheers for any assistance! This is my first time working with Java LTS. What would be the recommended way to handle this? This is my first time working with Java 3.11.