🚀 Lombok in Spring Boot — Complete Notes

1️⃣ What is Lombok?

Project Lombok is a Java library that reduces boilerplate code by automatically generating:

It works at compile time using annotations.

2️⃣ Why Do We Need Lombok in Spring Boot?

Without Lombok:

public class User {

    private Long id;
    private String name;

    public User() {}

    public User(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    // equals(), hashCode(), toString() ...
}

With Lombok:

import lombok.*;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Long id;
    private String name;
}

✅ Cleaner
✅ More readable
✅ Production-friendly

3️⃣ How to Add Lombok in Spring Boot

Maven Dependency

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

Gradle

compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'

4️⃣ Important Lombok Annotations (Most Used)

🔹 @Getter and @Setter

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class Product {
    private String name;
    private double price;
}

🔹 @ToString

@ToString
public class Product {
    private String name;
    private double price;
}
Product(name=Phone, price=50000.0)

🔹 @EqualsAndHashCode

Generates equals() and hashCode().

🔹 @NoArgsConstructor

@NoArgsConstructor
public class User {
    private String name;
}

🔹 @AllArgsConstructor

@AllArgsConstructor
public class User {
    private Long id;
    private String name;
}

🔹 @RequiredArgsConstructor ⭐

@Service
@RequiredArgsConstructor
public class UserService {

    private final UserRepository userRepository;
}

🔹 @Data

@Data
public class Employee {
    private Long id;
    private String name;
}

🔹 @Builder

@Data
@Builder
public class Order {
    private Long id;
    private String product;
    private int quantity;
}

🔹 @Value

@Value
public class Address {
    String city;
    String country;
}

🔹 Logging with @Slf4j

@Slf4j
@Service
public class UserService {

    public void test() {
        log.info("User service called");
    }
}

5️⃣ Lombok + Spring Boot Dependency Injection

FeatureBenefit
final fieldsImmutable dependency
Constructor injectionTestable
No @Autowired neededCleaner code

6️⃣ Lombok in JPA Entities ⚠ Important

❌ Avoid using @Data on JPA entities.

7️⃣ How Lombok Works (Behind the Scenes)

Your Code → Lombok Annotation Processor → Generated Bytecode → JVM
[Source Code]
      |
      v
[Lombok Annotation Processor]
      |
      v
[Compiled .class File]

9️⃣ Common Interview Questions

Q: Is Lombok safe in production?
✅ Yes.

Q: Does Lombok affect runtime performance?
❌ No.

🔟 Best Practices Summary

📚 Conclusion

Lombok reduces boilerplate and improves readability in modern Spring Boot development.