CodexBloom - Programming Q&A Platform

Spring Boot Application scenarios to Load Context Due to Circular Dependency with @Autowired Fields

šŸ‘€ Views: 86 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-14
spring-boot dependency-injection circular-dependency Java

I'm upgrading from an older version and Could someone explain I'm converting an old project and I've searched everywhere and can't find a clear answer. I'm working with a `BeanCurrentlyInCreationException` when trying to run my Spring Boot application, which suggests there's a circular dependency scenario between two beans. Specifically, I have two services, `UserService` and `NotificationService`, both of which are annotated with `@Service`. `UserService` depends on `NotificationService`, and `NotificationService` requires `UserService` through an `@Autowired` field. Here's a simplified version of my code: ```java @Service public class UserService { private final NotificationService notificationService; @Autowired public UserService(NotificationService notificationService) { this.notificationService = notificationService; } public void processUser(String userId) { // some logic notificationService.sendNotification(userId); } } @Service public class NotificationService { private final UserService userService; @Autowired public NotificationService(UserService userService) { this.userService = userService; } public void sendNotification(String userId) { // some logic } } ``` I've tried using `@Lazy` on one of the `@Autowired` annotations, like this: ```java @Autowired @Lazy public UserService userService; ``` But this only seems to suppress the exception without really solving the question, and I’m still not sure if my beans are being created in a valid order. I also considered refactoring to remove the direct dependency, but I’m struggling to find a clean way to do it without complicating the logic. The version of Spring Boot I'm using is 2.5.4. Any suggestions on how to resolve this circular dependency without compromising the design or making the code too convoluted? For context: I'm using Java on macOS. I'd really appreciate any guidance on this. I'm working with Java in a Docker container on Linux. I'm on CentOS using the latest version of Java. For reference, this is a production CLI tool. Thanks in advance!