Lombok - java.lang.StackOverflowError: null on toString method

You are having a circular reference in the toString method generated by Lombok.

  • Product is referencing Categorie on toString, which is referencing Product, and so on

You could use the exclude a property @ToString, but it is going to be deprecated soon, so use the @ToString.Exclude:

@Document
@Data @AllArgsConstructor @NoArgsConstructor @ToString
public class Product {
  ...

  @ToString.Exclude
  private Categorie categorie;

  ...
}

@Document
@Data @AllArgsConstructor @NoArgsConstructor @ToString
public class Categorie {
  ...

  @ToString.Exclude
  private Collection<Product> products=new ArrayList<>();

  ...
}

Lombok refs here and here


I assume the @ToString annotation tells some tool you’re using (Lombok?) to generate a toString method that prints the values of all the fields. Each of the classes refer to the other: Product has a Categorie and Categorie has a list of Product instances. So when the toString implementation prints a Categorie, it calls toString on each Product, which then calls toString on its Categorie, etc. Since Product presumably refers to a Categorie which includes that Product in its products list, the toString calls bounce back and forth until the stack overflows. The solution is to avoid printing either Categorie,products or Product.categorie from the toString method. If you’re using Lombok, try annotating Categorie.products with @ToString.Exclude.