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 Jain is Java Developer and has good knowledge of Core java,Spring Boot and Asp.net.

Request for Proposal

Name is required

Comment is required

Sending message..