liveBook · Manning

@data

As explained in Spring in Action, Sixth Edition

@Data is a Lombok annotation that generates common data-class methods and a constructor for a class.

@Data is a Lombok class annotation that keeps Java domain objects compact by generating common methods at compile time. It supplies getters, setters, equals(), hashCode(), toString(), and a constructor for final properties. section 2.1.1

A compact domain class

Annotating Ingredient with @Data provides the usual accessors and utility methods for its final id, name, and type fields without writing them manually. The same pattern defines Taco and TacoOrder objects; TacoOrder can still add its own addTaco method. section 2.1.1

Add Lombok to the project before using @Data:

  • Declare org.projectlombok:lombok as a project dependency. section 2.1.1
  • Exclude Lombok from the Spring Boot Maven plugin because its code generation happens at compile time, not runtime. section 2.1.1
Listing 2.1 Defining taco ingredients
package tacos;
 
import lombok.Data;
 
@Data
public class Ingredient {
  
  private final String id;
  private final String name;
  private final Type type;
  
  public enum Type {
    WRAP, PROTEIN, VEGGIES, CHEESE, SAUCE
  }
 
}

View the complete Ingredient class showing the import, @Data annotation, fields, and nested enum. section 2.1.1

How Spring in Action, Sixth Edition covers it

How deep it goes
Defines generated methods and compile-time behavior but does not show their generated implementations.
Examples
Uses Ingredient, Taco, and TacoOrder classes as concrete annotated domain objects.
What it assumes
Assumes Java classes and fields, and requires adding Lombok as a project dependency.
What you can do after
Apply it via Lombok to write slimmer Java domain classes while retaining common generated methods.
How it connects
Connects Lombok with Java domain objects, constructors, getters, setters, equals, hashCode, and toString.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.