Spring Boot with Lombok

Posted By : Ritik Jain | 09-Jul-2021

Project Lombok

 

Project Lombok is a Java library tool that generates annotations for minimizing the code used for creating functions like getters and setters methods, constructors, hashcode, equals, and toString methods, and so on. The library replaces these codes with easy-to-use annotations.

To use Lombok in our project, we need to download its maven dependency given below:-

<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <version>1.18.8</version>
   <scope>provided</scope>
</dependency>

 

There are many annotations available in Lombok like:-

  • @Getter, @Setter
  • @NoArgsConstructor, @AllArgsConstructor
  • @Data
  • @NotNull

 

@Data annotation is equivalent to combination of Lombok’s  @Getter + @Setter + @RequiredArgsConstructor + @ToString + @EqualsAndHashCode.

@Data
public class MessageDto {
  
  private Long id;
  
  private String message;

}

 

If we need to declare getter and setter for any model or DTO then we just use @Getter and @Setter annotation.

import lombok.Getter;
import lombok.Setter;

public class MessageDto {
  
  private Long id;
  
  @Getter @Setter
  private String message;

}

 

We can also use @Getter and @Setter annotations at the class level then Lombok generates getter and setter methods for all the fields.

import lombok.Getter;
import lombok.Setter;

@Gette
@Setter
public class MessageDto {
  
  private Long id;
  
  private String message;

}

 

We can use the @NoArgsConstructor annotation to generate the default constructor that takes no arguments. To generate a constructor with arguments for all the fields, use the  @AllArgsConstructor annotation.

import lombok.*;

@NoArgsConstructor
@AllArgsConstructor
public class MessageDto {
  
  private Long id;
  
  private String message;

}

 

Thanks 

About Author

Author Image
Ritik Jain

Ritik is an accomplished Backend Developer with extensive experience in Mean. He is proficient in Core Java, Spring-Boot, Hibernate, Node.js, Angular 2+, and various relational databases like MySQL and MongoDB. With his expertise in API implementations, webservices, development testing, and deployments, he has contributed to the successful completion of various client projects. Apart from his professional pursuits, Ritik is an enthusiastic gamer and keeps himself updated with the latest advancements in technology.

Request for Proposal

Name is required

Comment is required

Sending message..