All posts

Fix Infinite Loop in Spring Boot

Resolve infinite loops in Spring Boot applications caused by circular bean dependencies, JPA entity serialization, and @Transactional pitfalls.

Infinite Loops in Spring Boot

Spring Boot applications can fall into infinite loops in several sneaky ways. The two most common involve circular bean dependencies and bidirectional JPA entity serialization.

Bidirectional JPA + Jackson = StackOverflow

When two entities reference each other and Jackson tries to serialize them, you get infinite recursion:

@Entity
public class Author {
    @OneToMany(mappedBy = "author")
    private List<Book> books;
}

@Entity
public class Book {
    @ManyToOne
    private Author author;
}

Returning an Author from a REST controller will serialize books, which serializes each book's author, which serializes books again — forever.

The Fix

Use @JsonManagedReference and @JsonBackReference:

@Entity
public class Author {
    @OneToMany(mappedBy = "author")
    @JsonManagedReference
    private List<Book> books;
}

@Entity
public class Book {
    @ManyToOne
    @JsonBackReference
    private Author author;
}

Alternatively, use DTOs instead of exposing entities directly — this is the preferred approach for production APIs.

Circular Bean Dependencies

Spring will throw BeanCurrentlyInCreationException at startup if two beans depend on each other via constructor injection. Fix it with @Lazy on one dependency:

@Service
public class OrderService {
    public OrderService(@Lazy PaymentService paymentService) {
        this.paymentService = paymentService;
    }
}

Bugsly captures StackOverflowError events with full stack traces, making it easy to see the repeating serialization frame that reveals the cycle.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free