8 Essential Lombok Annotations to Slash Boilerplate in Spring Boot

This article walks through eight core Lombok annotations—@Data, @Getter/@Setter, @Builder, @AllArgsConstructor/@NoArgsConstructor, @Slf4j, @RequiredArgsConstructor, plus two optional ones—showing real‑world Spring Boot examples, common pitfalls, team conventions, and when to avoid Lombok.

CodeNotes
CodeNotes
CodeNotes
8 Essential Lombok Annotations to Slash Boilerplate in Spring Boot

0. Preparation

Add the Lombok dependency (Spring Boot manages the version) and enable annotation processing in the IDE (Settings → Build → Compiler → Annotation Processors → Enable). Without it the code will show errors.

Maven multi‑module projects should align Lombok version in the parent POM to avoid inconsistent processing.

Gradle projects must configure both compileOnly and annotationProcessor dependencies; missing either can cause IDE success but command‑line compilation failure.

1. @Data

Bad example : manually writing getter/setter, toString, equals, hashCode results in dozens of repetitive lines.

Good example :

@Data
public class UserDTO {
    private Long id;
    private String nickname;
    private String phone;
}

The annotation automatically generates getter, setter, toString, equals, and hashCode, making it the default choice for DTOs and VOs.

2. @Getter / @Setter

Use when you need fine‑grained control, e.g., immutable aggregate roots where only specific fields may be mutated:

@Getter
public class Order {
    private final Long id;
    private BigDecimal amount;
    @Setter private String remark; // only remark can be changed
}

3. @Builder

Ideal for constructors with many parameters. Example of a typical order‑creation command:

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class OrderCreateCmd {
    private Long userId;
    private Long skuId;
    @Builder.Default private Integer count = 1; // default value
    private Long addrId;
    private Long couponId;
    private String channel;
}

OrderCreateCmd cmd = OrderCreateCmd.builder()
        .userId(1001L)
        .skuId(2002L)
        .addrId(3003L)
        .channel("APP")
        .build();

Combining @Data @Builder @NoArgsConstructor @AllArgsConstructor yields a four‑annotation bundle compatible with JSON, MyBatis, and the builder pattern.

4. @AllArgsConstructor / @NoArgsConstructor

@NoArgsConstructor

: required for JSON deserialization and JPA/MyBatis entities. @AllArgsConstructor: creates a full‑field constructor useful for the builder.

5. @Slf4j

Replaces manual logger declaration. Bad example:

private static final Logger log = LoggerFactory.getLogger(UserService.class);

Good example:

@Slf4j
@Service
public class UserService {
    public void register(String phone) {
        log.info("User registration, phone={}", phone);
    }
}

6. @RequiredArgsConstructor

Provides the preferred constructor‑injection pattern. Bad example uses field injection with @Autowired, leading to mutable dependencies and hidden circular references.

@Service
@RequiredArgsConstructor
public class OrderService {
    private final UserService userService;
    private final StockService stockService;
    private final OrderMapper orderMapper;
}

Benefits: immutable fields, easier testing (constructor‑based mocks), and immediate detection of circular dependencies.

Additional optional annotations (use with caution)

@SneakyThrows

Suppresses checked exceptions, suitable only for “almost never fails” scenarios such as reading a static config file.

@SneakyThrows
public String readConfig() {
    return Files.readString(Paths.get("app.conf")); // no throws clause
}

@Accessors(chain = true)

Enables fluent setters, handy for building test data or DTOs:

@Data
@Accessors(chain = true)
public class UserDTO {
    private String nickname;
    private Integer age;
}

UserDTO u = new UserDTO().setNickname("Tom").setAge(18);

Note: may conflict with older JSON libraries or MyBatis reverse‑generation; use on DTO/Builder classes only.

Common pitfalls (real‑world pain points)

@Data on JPA/MyBatis entities : equals/hashCode include all fields, causing StackOverflowError on bidirectional relationships. Prefer hand‑written methods or @EqualsAndHashCode(of = "id").

@Builder with inheritance : fields from superclasses are lost; use @SuperBuilder instead.

@Builder default values : plain field initializers are ignored; annotate with @Builder.Default.

Inconsistent Lombok setup : if a team member forgets the IDE plugin, the project fails to compile.

@Slf4j in abstract classes : not inherited; subclasses must annotate again.

Team conventions

DTO/VO default bundle: @Data @Builder @NoArgsConstructor @AllArgsConstructor.

Service classes: use final fields with @RequiredArgsConstructor, avoid field injection.

Entity classes: avoid @Data; prefer @Getter/@Setter and explicitly define equals/hashCode based on primary‑key fields.

Embedding these three rules in a README or project scaffold ensures uniform style and halves code‑review effort.

When NOT to use Lombok

Public libraries or SDKs where downstream projects may not enable annotation processing.

Highly audited core domain models (e.g., risk, billing) where explicit code aids debugging and compliance.

Legacy codebases with fragmented team knowledge; introduce Lombok only after a consensus on conventions.

Rule of thumb: apply Lombok where boilerplate is abundant and team agreement is strong; refrain where external contracts or readability are paramount.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

spring-bootAnnotationsBuilderBoilerplate Reduction
CodeNotes
Written by

CodeNotes

Discuss code and AI, and document daily life and personal growth.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.