Skip to content
lombok-patterns logo

Lombok Patterns

lombok-patterns

Lombok annotations and best practices for Java 21+ projects. Use when reducing boilerplate, configuring builders, or choosing between Lombok and Records.

SKILL.md

Full skill instructions

Lombok Patterns

This skill provides guidance on using Project Lombok to reduce boilerplate code in Java applications, covering annotations, best practices, and integration patterns.

Note: This guide targets Java 21+ projects. Some Lombok features are now obsolete due to modern Java features (Records, var, try-with-resources). See Java 21+ Considerations below.

Overview

Lombok is a Java library that automatically generates common code like getters, setters, constructors, builders, and more during compilation. It helps create cleaner, more maintainable code.

Java 21+ Considerations

Some Lombok features are now redundant with modern Java:

Lombok FeatureJava AlternativeRecommendation
val/varvar (Java 10+)Use Java var
@Valuerecord (Java 16+)Prefer records for simple value objects
@Datarecord (Java 16+)Prefer records for simple DTOs
@Cleanuptry-with-resources (Java 7+)Use try-with-resources
@Withrecord wither methodsRecords can define wither methods

When Lombok Still Adds Value

  • JPA Entities: Records don't work with JPA (need no-arg constructor, mutable state)
  • @Builder: Records don't have built-in builder support
  • @Slf4j: No Java equivalent for logger generation
  • @RequiredArgsConstructor: Useful for Spring dependency injection
  • Inheritance: Records can't extend classes

Annotation Categories

Core Annotations (Still Valuable)

AnnotationPurposeUse Case
@Getter/@SetterAccessor methodsJPA entities, mutable classes
@NoArgsConstructorNo-argument constructorJPA entities, serialization
@AllArgsConstructorAll-fields constructorDependency injection
@RequiredArgsConstructorConstructor for final/​@NonNull fieldsSpring services
@BuilderBuilder pattern implementationComplex object construction

Consider Java Records Instead

LombokUse Java Record When
@ValueSimple immutable data carriers
@DataSimple DTOs without inheritance
// ✅ Prefer Java Record for simple value objects
public record Money(BigDecimal amount, String currency) {}

// ✅ Prefer Java Record for simple DTOs
public record CustomerDTO(String name, String email) {}

// ✅ Use Lombok for JPA entities (records don't work with JPA)
@Entity
@Getter
@Setter
@NoArgsConstructor
public class Customer {
    @Id private Long id;
    private String name;
}

Logging Annotations

AnnotationLogger Type
@Slf4jSLF4J (recommended)
@Log4j2Log4j 2
@Logjava.util.logging
@CommonsLogApache Commons Logging

Field & Method Annotations

AnnotationPurpose
@NonNullNull checks on parameters/​fields
@WithImmutable setters (creates new instance)
@SneakyThrowsThrow checked exceptions without declaration
@SynchronizedThread-safe method synchronization
@ToStringCustomizable toString() generation
@EqualsAndHashCodeCustomizable equals/​hashCode

Quick Reference

JPA Entities (Lombok Recommended)

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class Product {
    @Id
    @EqualsAndHashCode.Include
    private Long id;

    private String name;
    private BigDecimal price;
}

Spring Services

@Service
@RequiredArgsConstructor
@Slf4j
public class OrderService {
    private final OrderRepository orderRepository;
    private final PaymentService paymentService;

    public Order process(Order order) {
        log.info("Processing order: {}", order.getId());
        return orderRepository.save(order);
    }
}

Builder Pattern (Lombok Adds Value)

// Records don't have builder support - use Lombok
@Builder
public record Email(
    String to,
    String subject,
    String body,
    @Singular List<String> attachments
) {}

// Usage
Email email = Email.builder()
    .to("[email protected]")
    .subject("Hello")
    .body("Content")
    .attachment("file1.pdf")
    .build();

Best Practices

✅ Do

  • Use Java Records for simple value objects and DTOs
  • Use @RequiredArgsConstructor with final fields for dependency injection
  • Use @Slf4j for logging instead of manual logger creation
  • Use @Builder for classes with many optional fields
  • Be explicit with @EqualsAndHashCode on JPA entities

❌ Avoid

  • Using @Data or @Value when a Java Record would suffice
  • Using @Data on JPA entities (use individual annotations)
  • Using @EqualsAndHashCode with lazy-loaded JPA relationships
  • Overusing @SneakyThrows (makes exception handling unclear)

Common Pitfalls

PitfallProblemSolution
@Data on entitiesIncludes mutable setters, problematic equals/​hashCodeUse @Getter, @Setter, explicit @EqualsAndHashCode
Missing @NoArgsConstructorJPA/​Jackson need no-arg constructorAlways add with @AllArgsConstructor
Circular @ToStringStackOverflow with bidirectional relationshipsUse @ToString.Exclude on one side
Using Lombok for simple DTOsAdds unnecessary dependencyUse Java Records instead

Cookbook Index

Core Annotations

Field & Method Annotations

Integration Patterns

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View