BBackend CourseLeroy Labs
0/0
Search the course

Modern Java for backend work (records, Lombok, Java 25)

Records, sealed types, switch expressions, unnamed variables, Lombok and when to use each. All your projects run Java 25.

● beginnerSpring-Boot-StoreHostel-Web-AppReport-Manager-2SperoTek (in dev)

The concept

All five of your backends target Java 25. Modern Java removes most of the boilerplate that Lombok used to exist for.

Records: immutable data carriers

public record CreateBookingRequest(
        @NotNull UUID roomId,
        @Pattern(regexp = "\\d{4}/\\d{4}") String academicYear,
        @Pattern(regexp = "FIRST|SECOND|FULL") String semester) {}

A record gives you a constructor, accessors (roomId()), equals, hashCode and toString, and every field is final. That makes records ideal for DTOs, events and value objects. They are not suitable for JPA entities, because JPA needs a no-arg constructor, mutable state and proxies.

Compact constructors for invariants

public record Money(BigDecimal amount, String currency) {
    public Money {
        if (amount.scale() > 4) throw new IllegalArgumentException("max 4 decimals");
        Objects.requireNonNull(currency);
    }
}

Switch expressions and pattern matching

PaymentStatus status = switch (event.getType()) {
    case "payment_intent.succeeded"      -> PaymentStatus.PAYED;
    case "payment_intent.payment_failed" -> PaymentStatus.FAILED;
    default -> throw new IllegalStateException("Unhandled " + event.getType());
};

Sealed interfaces: closed hierarchies

sealed interface Posting permits Debit, Credit {}
record Debit(UUID account, BigDecimal amt) implements Posting {}
record Credit(UUID account, BigDecimal amt) implements Posting {}
// switch over Posting is exhaustive, so the compiler catches a missing case

Unnamed variables (_) and instance main

(_, response, _) -> response.sendError(401)   // ignore params you don't need

Virtual threads (Java 21+)

spring.threads.virtual.enabled=true lets Tomcat serve each request on a cheap virtual thread, which is great for I/O-bound apps. The bonus concurrency lesson covers this.

In your projects

Hostel-Web-AppHostelBackendApplication.java · config/SecurityConfig.java

Hostel uses the instance-main style (static void main without public/String[] ceremony) and unnamed lambda parameters in the security handlers: (_, res, _) -> .... Request DTOs are records with Bean Validation, e.g. CreateBookingRequest.

SperoTek (in dev)*/web/dto/*Dtos.java · shared/domain/Money.java

SperoTek groups each module’s DTOs as nested records in one file (AuthDtos, JournalDtos, AccountDtos). Events are records too (JournalPosted, CompanyCreated), and Money is a value object.

Spring-Boot-Storedtos/RegisterUserRequest.java

Spring-Boot-Store uses Lombok @Data classes for DTOs instead of records. They work, but they are mutable and generate setters you don’t need.

Lombok: what you still use it for

Annotation Used for Records replace it?
@RequiredArgsConstructor Constructor injection in services No (still handy)
@Getter / @Setter on entities JPA entities No (entities can’t be records)
@Slf4j / @Log4j2 Logger field No
@Data on DTOs DTOs Yes, prefer records
@EqualsAndHashCode(onlyExplicitlyIncluded = true) Entity equality (Store) n/a

Alternatives

  • Kotlin: data classes, null-safety and coroutines. It is fully Spring-compatible, and you already use it for PostureCam.
  • Immutables / AutoValue: annotation processors for value types, made mostly obsolete by records.
  • Immutability and thread safety. Immutable objects can be shared across threads freely.
  • Optional. Use it for return types like Optional<Room> findByIdForUpdate(), not for fields or parameters.
  • Streams vs loops. Readability first; streams aren’t automatically faster.
  • BigDecimal for money. Never double. See the money lesson in Module 3.
  • JSpecify / nullness annotations. SperoTek includes JSpecify to mark @Nullable explicitly.

Check yourself

1. Why not make a JPA entity a record?
2. Benefit of a sealed interface + switch?