How to use Lambok in Spring Boot - onlyxcodes

Friday 9 April 2021

How to use Lambok in Spring Boot

Hi here at all, I'll teach you how to use Lambok in Spring Boot in this tutorial. Project Lombok is a fantastic Java library built to help developers operate faster.


Lambok library eliminates boilerplate code in Java such as getters, setters, and the method toString code, saving space by creating code in a ".class" file rather than the source code file.


In this post, you'll learn how to use this library's features to prevent boilerplate code while using them on simple examples in a spring boot project.


how to use lambok in spring boot - maven - lambok maven - lambok jar -   lambok builder - lambok annotations - lambok data - lambok comparable

What is Project Lambok?

Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.  Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more. ( note is taken from the official site).


Simply Understand by Below term.


The time spent writing boilerplate code in Java, such as getter, setter, constructor, and method toString() native code will be reduced by Project Lombok.


What is boilerplate code?

In computer programming, boilerplate code or just boilerplate are sections of code that are repeated in multiple places with little to no variation. When using languages that are considered verbose, the programmer must write a lot of code to accomplish only minor functionality. Such code is called boilerplate ( Wikipedia definition )


How Does Project Lambok Features Work?


You must add annotations to your classes to use any of Project Lombok's features. The annotations tell Project Lombok which boilerplate code you want it to write for you.


Let's assume you have a class and don't want to manually apply the Getter and Setter methods. Simply add the @Getter and @Setter to the top of your class, and Project Lombok can use the fields in your class to execute the Getter and Setter methods behind the exhibitions.


Depending on your choice, you can use Spring Tool Suite IDE (STS), Eclipse, or IntelliJ IDEs. I prefer STS.


Setup Project Lambok to Spring Tool Suite

Step 1: Download Lambok from the official Lambok website.


Step 2: After the lambok jar file has been downloaded full, go to your download folder path and double click on the lambok jar file.


double click on the lambok jar file

Step 3: Check that the lambok installer is running and that your system's IDEs are up to date. It's scanning my Eclipse IDE right now.


lambok installer is running

Step 4: However, I want to set up lambok in Spring Tool Suite (STS), so I press the specify location button to specify the Spring Tool Suite executable file location.


I press the specify location button

Step 5: Look, a custom window has opened, and I'm selecting the Spring Tool Suite executable file from my defined drive path in STS.


selecting the Spring Tool Suite executable file

Step 6: I unchecked the Eclipse checkbox after selecting the Spring Tool Suite executable file because I only want to configure the lambok STS tool.


Finally, click on the Install/Update button.


unchecked the eclipse checkbox

Step 7: See the lambok installer's custom window, which shows the message Installation Successful.


lambok gui shows the message Installation Successful.

Step 8: Restart your Spring Tool Suite IDE


restart your spring tool suite ide

Step 9: Go to the Spring Tool Suite, select help, and then about the Spring Tool Suite to double-check the installation. There is a project Lombok installation here.


select help -> about in sts

See lambok installed completely.


see lambok installed completely in STS  about page

Setup lambok in IntelliJ IDE


Step 1: Navigate to File > Settings > Plugins


File > Settings > Plugins in intellij

Step 2: Search for Lombok plugin


Step 3: Click on Install Plugin


search for lombok plugin. click on install plugin. restart intelliJ idea


Step 4: Restart IntelliJ IDEA


Let’s look at how to use lambok in Spring Boot.


I'm assuming you've set up lambok properly in your STS.


Creating New Spring Boot Project

Note: You must be able to connect to the internet.


Step 1 - Start Spring Too Suite Tool. On the left, press the Create New Spring Starter Project button. Otherwise, select File -> New -> Spring Starter Project from the File menu.


create a new spring boot starter project

Step 2 - Configure the project in the second phase, as seen in the example below. After entering the details, click on the Next button.


Name – LambokSpringBootDemo


Group – com.onlyxcodes


Description – How to use Lambok in Spring Boot


Package – com.onlyxcodes.lambokapp


entering the project details

Step 3 - The third step is to choose custom jar files. I haven't chosen any jar files because they aren't needed for this post.


choose custom jar files

Step 4 - Finally, press the Finish button to complete the project setup.


press the finish button

See the complete project directory structure, as well as the additional packages we'll build in this project, ahead.


project directory structure

The final step is to make sure that Lombok init scripts are included in the compiler's classpath. We used Maven, so the lambok dependency can be applied to the pom.xml.


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


pom.xml

Since we're using Maven, Spring Boot can configure all of our dependencies for us.


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.4</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.onlyxcodes</groupId>
	<artifactId>LambokSpringBootDemo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>LambokSpringBootDemo</name>
	<description>How to use Lambok Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
		<dependency>
		    <groupId>org.projectlombok</groupId>
		    <artifactId>lombok</artifactId>
		    <version>1.18.20</version>
		    <scope>provided</scope>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Let's get started with Lambok Annotation.


Annotations are available on Lombok. Some of the annotations apply to daily coding. Let's take a look at a couple of examples.


@Getter and @Setter Annotations:


The use of public getter and setter methods to encapsulate object properties is a popular Java practice.

Both @Getter and @Setter annotations in Project Lombok automate the creation of getters and setters of non-static fields in your POJOs, as their names indicate. 


The @Setter annotation will build a method called setRollno to enable developers to switch the value of the rollno field in this article. The @Getter annotation, on the other hand, produces a getRollno method that returns the value for the person who asked. 

Note: Since Lombok follows conventions, if rollno is a boolean, the getter accessor will be called isRollno rather than getRollno.


Look into it. Inside the com.onlyxcodes.lambokapp.model package, build the Student class and add the following code to it.


code [ without lambok features ]


package com.onlyxcodes.lambokapp.model;

public class Student {

	private int rollno;
	private String name;
	private String position;
	
	public int getRollno() {
		return rollno;
	}
	public void setRollno(int rollno) {
		this.rollno = rollno;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPosition() {
		return position;
	}
	public void setPosition(String position) {
		this.position = position;
	}
	
}

Code with Lambok annotations:


package com.onlyxcodes.lambokapp.model;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class StudentWithLambok {
	
	private int rollno;
	private String name;
	private String position;
}

To make sure it's running, open the spring boot main class from the com.onlyxcodes.lambokapp packages and make the following changes.


package com.onlyxcodes.lambokapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.onlyxcodes.lambokapp.model.StudentBuilderClassLevel;
import com.onlyxcodes.lambokapp.model.StudentBuilderConstructorLevel;
import com.onlyxcodes.lambokapp.model.StudentBuilderMethodLevel;
import com.onlyxcodes.lambokapp.model.StudentWithLambok;

import lombok.AllArgsConstructor;

@SpringBootApplication
public class LambokSpringBootDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(LambokSpringBootDemoApplication.class, args);
		
		System.out.println();
		System.out.println("------------------------- test @Setter and @Getter annotation method ---------------------------------");
		
		StudentWithLambok lambokGS = new StudentWithLambok();
		
		//test getter and setter methods
		lambokGS.setRollno(50);
		lambokGS.setName("Hamid");
		lambokGS.setPosition("Programmer");
		
		System.out.println(lambokGS.getRollno());
		System.out.println(lambokGS.getName());
		System.out.println(lambokGS.getPosition()); 
	}
}

See Output:


@Getters and @Setters annotation output

@ToString Annotation:


At compile time, this annotation activates the toString() method code in the ".class" file. The class name and fields are displayed in sequence, comma-separated, in the default integration.


We don't need to retain the toString() method code if we use the @ToString annotation to expand POJO properties.

On a typical day, the code will look like this: [ code without lambok features ]


package com.onlyxcodes.lambokapp.model;

public class Student {

	private int rollno;
	private String name;
	private String position;
	
	//toString method 
	@Override
	public String toString() {
		return "Student [rollno=" + rollno + ", name=" + name + ", position=" + position + "]";
	}
}

We could use the @ToString annotation to code using Lamok. [ code with lambok features ]


package com.onlyxcodes.lambokapp.model;

import lombok.ToString;

@ToString
public class StudentWithLambok {
	
	private int rollno;
	private String name;
	private String position;
}

To make sure the @ToString annotation is working properly, go back to the Spring Boot main class and make the following changes.


package com.onlyxcodes.lambokapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.onlyxcodes.lambokapp.model.StudentBuilderClassLevel;
import com.onlyxcodes.lambokapp.model.StudentBuilderConstructorLevel;
import com.onlyxcodes.lambokapp.model.StudentBuilderMethodLevel;
import com.onlyxcodes.lambokapp.model.StudentWithLambok;

import lombok.AllArgsConstructor;

@SpringBootApplication
public class LambokSpringBootDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(LambokSpringBootDemoApplication.class, args);
		
		System.out.println();
		System.out.println("------------------------- test @toString annotation method ---------------------------------");
		System.out.println(); 
		
		//test toString method
		StudentWithLambok lamboktoString = new StudentWithLambok();
		
		lamboktoString.setRollno(50);
		lamboktoString.setName("Hamid");
		lamboktoString.setPosition("Programmer");
		
		System.out.println(lamboktoString.toString()); 	
	}
}

See Output:


@tostring annotation output

@NoArgsConstructor Annotations:


This annotation is used to build a constructor that has no parameters (no arguments on it). The body is blank and it does nothing. It's most commonly used in combination with another parameterized constructor.


It's required if you want to create a class object without passing any arguments to the constructor. 



See Java code [ without lambok features ]


package com.onlyxcodes.lambokapp.model;

public class Student {

	private int rollno;
	private String name;
	private String position;
	
	public Student() {
		super();
	}
	
}

Lambok creates an empty constructor when you write code with lambok features. [ code with lambok annotation]


package com.onlyxcodes.lambokapp.model;

import lombok.NoArgsConstructor;

@NoArgsConstructor
public class StudentWithLambok {
	
	private int rollno;
	private String name;
	private String position;

}

Put this annotation to the test. update the following codes in the spring boot main class


package com.onlyxcodes.lambokapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.onlyxcodes.lambokapp.model.StudentBuilderClassLevel;
import com.onlyxcodes.lambokapp.model.StudentBuilderConstructorLevel;
import com.onlyxcodes.lambokapp.model.StudentBuilderMethodLevel;
import com.onlyxcodes.lambokapp.model.StudentWithLambok;

import lombok.AllArgsConstructor;

@SpringBootApplication
public class LambokSpringBootDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(LambokSpringBootDemoApplication.class, args);
		
		System.out.println();
		System.out.println("------------------------- test @NoArgsConstructor annotation method ---------------------------------");
		
		//test @NoArgsConstructor 
		StudentWithLambok lambokNoArgumentConstructor = new StudentWithLambok();
		System.out.println(lambokNoArgumentConstructor.getRollno());
		System.out.println(lambokNoArgumentConstructor.getName());
		System.out.println(lambokNoArgumentConstructor.getPosition()); 
		
	}
}

As you can see from the output, this annotation prints null values.


@NoArgsConstructor annotations output

@AllArgsConstructor Annotation:


This annotation is used to make a parameterized constructor with all of the class's fields.


This constructor takes a single parameter and uses it to load every field. It's necessary if you want to create a class object by passing the fields' primary values to the constructor.


Code [ without lambok features ]


package com.onlyxcodes.lambokapp.model;

public class Student {

	private int rollno;
	private String name;
	private String position;
	
	
	public Student(int rollno, String name, String position) {
		super();
		this.rollno = rollno;
		this.name = name;
		this.position = position;
	}
	
}

In this case, simply adding @AllArgsConstructor causes Lombok to build a constructor that retrieves values for all three given fields (rollno, name, and position).


Code with lambok features


package com.onlyxcodes.lambokapp.model;

import lombok.AllArgsConstructor;

@AllArgsConstructor
public class StudentWithLambok {
	
	private int rollno;
	private String name;
	private String position;
}

Let's put the @AllArgsConstructor annotation to the test once more. update the following codes in the spring boot main class 


package com.onlyxcodes.lambokapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.onlyxcodes.lambokapp.model.StudentBuilderClassLevel;
import com.onlyxcodes.lambokapp.model.StudentBuilderConstructorLevel;
import com.onlyxcodes.lambokapp.model.StudentBuilderMethodLevel;
import com.onlyxcodes.lambokapp.model.StudentWithLambok;

import lombok.AllArgsConstructor;

@SpringBootApplication
public class LambokSpringBootDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(LambokSpringBootDemoApplication.class, args);
		
		System.out.println();
		System.out.println("------------------------- test @AllArgsConstructor annotation method ---------------------------------");
		System.out.println();
		
		//test @AllArgsConstructor constructor
		StudentWithLambok lambokArgumentConstructor = new StudentWithLambok(52, "Hamid", "Programmer");
		System.out.println(lambokArgumentConstructor.toString()); 
		
	}

}

As you can see in the output, this annotation prints all of the fields' values.


@AllArgsConstructor annotation output

@EqualsAndHashCode Annotation:


This is, without a doubt, one of Lombok's coolest features. You can have Lombok generate the equals and hashcode methods for you by using the @EqualsAndHashCode annotation in your classes.


To specify a custom equality-checking process, use the equals and hashcode methods in the class below. You'd usually do something like this if you weren't on Lombok:


Code [ without lambok features ]


package com.onlyxcodes.lambokapp.model;

public class Student {

	private int rollno;
	private String name;
	private String position;
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + ((position == null) ? 0 : position.hashCode());
		result = prime * result + rollno;
		return result;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (position == null) {
			if (other.position != null)
				return false;
		} else if (!position.equals(other.position))
			return false;
		if (rollno != other.rollno)
			return false;
		return true;
	}
	
}

Code with lambok features:


package com.onlyxcodes.lambokapp.model;

import lombok.EqualsAndHashCode;

@EqualsAndHashCode
public class StudentWithLambok {
	
	private int rollno;
	private String name;
	private String position;

}

Update the following code within the spring boot main class to evaluate @Equal and @EqualsAndHashCode annotation. 


package com.onlyxcodes.lambokapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.onlyxcodes.lambokapp.model.StudentBuilderClassLevel;
import com.onlyxcodes.lambokapp.model.StudentBuilderConstructorLevel;
import com.onlyxcodes.lambokapp.model.StudentBuilderMethodLevel;
import com.onlyxcodes.lambokapp.model.StudentWithLambok;

import lombok.AllArgsConstructor;

@SpringBootApplication
public class LambokSpringBootDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(LambokSpringBootDemoApplication.class, args);
		
		System.out.println();
		System.out.println("------------------------- test @Equals annotation method ---------------------------------");
		
		//test equals method
		StudentWithLambok lambokTest1 = new StudentWithLambok();
		
		lambokTest1.setRollno(50);
		lambokTest1.setName("Hamid");
		lambokTest1.setPosition("Programmer");
		
		StudentWithLambok lambokTest2 = new StudentWithLambok();
		
		lambokTest2.setRollno(50);
		lambokTest2.setName("Hamid");
		lambokTest2.setPosition("Programmer");
		
		System.out.println(lambokTest1.equals(lambokTest2));
		
		System.out.println();
		System.out.println("------------------------- test @EqualsAndHashCode annotation method ---------------------------------");
		
		//test EqualAndHasCode method
		System.out.println(lambokTest1.hashCode());
		System.out.println(lambokTest2.hashCode()); 
		
	}

}

As you can see, these annotations produce the same results.


@EqualsAndHashCode annotation output

@Builder Annotation:


The @Builder annotation allows you to generate the code needed to make your class instantiable automatically. 


We'll see how to use this annotation at the class, constructor, and method levels in this example.


1. Lombok @Builder using at Class level


Here I created a new class called UserBuilderClassLevel within packages com.onlyxcodes.lambokapp.model.

This is the builder class, and it's used to create examples of your class. If we're to modify the name of the builder class, we must use the @Builder(builderClassName = "Builder") annotation.

To change the name of build(), use the @Builder(buildMethodName = "make") attribute. To change the name of builder(), use the @Builder(builderMethodName = "person") attribute.


package com.onlyxcodes.lambokapp.model;

import lombok.Builder;
import lombok.Getter;

@Getter
@Builder
public class StudentBuilderClassLevel {
	
	private int rollno;
	private String name;
	private String position;
	
}

Update the following code in the spring boot main class to evaluate @Builder class-level annotation.


package com.onlyxcodes.lambokapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.onlyxcodes.lambokapp.model.StudentBuilderClassLevel;
import com.onlyxcodes.lambokapp.model.StudentBuilderConstructorLevel;
import com.onlyxcodes.lambokapp.model.StudentBuilderMethodLevel;
import com.onlyxcodes.lambokapp.model.StudentWithLambok;

import lombok.AllArgsConstructor;

@SpringBootApplication
public class LambokSpringBootDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(LambokSpringBootDemoApplication.class, args);
		
		System.out.println();
		System.out.println("------------------------- test @Builder annotation using class level ---------------------------------");
		
		
		//test builder method
		StudentBuilderClassLevel lambokBuilderClassLevel = StudentBuilderClassLevel.builder()
				.rollno(40)
				.name("hamid")
				.position("programmer")
				.build();
		
		System.out.println("rollno => "+lambokBuilderClassLevel.getRollno());
		System.out.println("name => "+lambokBuilderClassLevel.getName());
		System.out.println("position => "+lambokBuilderClassLevel.getPosition()); 
		
	}

}

Output:



@builder class level annotation output - builder

2. Lombok @Builder using at Constructor level


If only a few of the fields are needed to initialize your class, use the @Builder annotation at the constructor level to specify the needed arguments. 


Let's look at an illustration from the StudentBuilderConstructorLevel class. This class is part of the com.onlyxcodes.lambokapp.model package.


package com.onlyxcodes.lambokapp.model;

import lombok.Builder;
import lombok.Getter;

@Getter
public class StudentBuilderConstructorLevel {
	
	private int rollno;
	private String name;
	private String position;
	
	@Builder
	public StudentBuilderConstructorLevel(int rollno, String name, String position) {
		super();
		this.rollno = rollno;
		this.name = name;
		this.position = position;
	}
}

To see the output of the @Builder constructor level annotation, go back to the spring boot main class and update the following code.


package com.onlyxcodes.lambokapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.onlyxcodes.lambokapp.model.StudentBuilderClassLevel;
import com.onlyxcodes.lambokapp.model.StudentBuilderConstructorLevel;
import com.onlyxcodes.lambokapp.model.StudentBuilderMethodLevel;
import com.onlyxcodes.lambokapp.model.StudentWithLambok;

import lombok.AllArgsConstructor;

@SpringBootApplication
public class LambokSpringBootDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(LambokSpringBootDemoApplication.class, args);
		
		System.out.println();
		System.out.println("------------------------- test @Builder annotation using constructor level ---------------------------------");
		
		
		StudentBuilderConstructorLevel lambokBuilderConstructorLevel = StudentBuilderConstructorLevel.builder()
				.rollno(10)
				.name("hamid")
				.position("designer")
				.build();
		
		System.out.println("rollno => "+lambokBuilderConstructorLevel.getRollno());
		System.out.println("name => "+lambokBuilderConstructorLevel.getName());
		System.out.println("position => "+lambokBuilderConstructorLevel.getPosition());
		
	}

}

Output:



@Builder constructor level annotation output | builder

3. Lombok @Builder using at Method level


If your class has an instance-creation method, you can transform it into a builder by declaring @Builder on it.


Let's look at an example from the StudentBuilderMethodLevel class. This class is part of the com.onlyxcodes.lambokapp.model package.

We'll look to create an instance with the default rollno and status. 


package com.onlyxcodes.lambokapp.model;

import lombok.Builder;
import lombok.Getter;

@Getter
public class StudentBuilderMethodLevel {
	
	private int rollno;
	private String name;
	private String position;
	private boolean status;
	
	public StudentBuilderMethodLevel(int rollno, String name, String position, boolean status) {
		super();
		this.rollno = rollno;
		this.name = name;
		this.position = position;
		this.status = status;
	}

	@Builder(builderMethodName = "builder")
	public static StudentBuilderMethodLevel createInstance(int rollno, String name, String position) {
		
		return new StudentBuilderMethodLevel(25, name, position, true);
	}
	
}

In spring boot main class updates codes, test the third @Builder annotation at the Method level as follows. 


package com.onlyxcodes.lambokapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.onlyxcodes.lambokapp.model.StudentBuilderClassLevel;
import com.onlyxcodes.lambokapp.model.StudentBuilderConstructorLevel;
import com.onlyxcodes.lambokapp.model.StudentBuilderMethodLevel;
import com.onlyxcodes.lambokapp.model.StudentWithLambok;

import lombok.AllArgsConstructor;

@SpringBootApplication
public class LambokSpringBootDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(LambokSpringBootDemoApplication.class, args);
		
		System.out.println();
		System.out.println("------------------------- test @Builder annotation using method level ---------------------------------");
		
		
		StudentBuilderMethodLevel lambokBuilderMethodLevel = StudentBuilderMethodLevel.builder()
				.rollno(25)
				.name("hamid")
				.position("designer")
				.build();
		
		System.out.println("rollno => "+lambokBuilderMethodLevel.getRollno());
		System.out.println("name => "+lambokBuilderMethodLevel.getName());
		System.out.println("position => "+lambokBuilderMethodLevel.getPosition());
		System.out.println("status => "+lambokBuilderMethodLevel.isStatus()); 
		
	}

}

Output:



@builder method level annotation output

@Data Annotation:


The @Data annotation is the one you'll hear about in this tutorial.


This annotation combines the @ToString, @EqualsAndHashCode, @Getter, @Setter, @AllArgsConstructor, and @NoArgsConstructor annotations into one convenient package. To put it another way, by using this annotation, you can render Lombok: 


  • override the toString() method; 
  • describe the equals and hashcode methods;
  • Develop getters and setters for the fields in your class.
  • For all non-initialized and non-nullable fields, describe a constructor 

code [ without lambok features ]


package com.onlyxcodes.lambokapp.model;

public class Student {

	private int rollno;
	private String name;
	private String position;
	
	public Student(int rollno, String name, String position) {
		super();
		this.rollno = rollno;
		this.name = name;
		this.position = position;
	}

	public int getRollno() {
		return rollno;
	}

	public void setRollno(int rollno) {
		this.rollno = rollno;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPosition() {
		return position;
	}

	public void setPosition(String position) {
		this.position = position;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + ((position == null) ? 0 : position.hashCode());
		result = prime * result + rollno;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (position == null) {
			if (other.position != null)
				return false;
		} else if (!position.equals(other.position))
			return false;
		if (rollno != other.rollno)
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "Student [rollno=" + rollno + ", name=" + name + ", position=" + position + "]";
	}
		
}

code with @Data lambok features


As you can see, the annotation covered the boilerplate code in the kit. 


package com.onlyxcodes.lambokapp.model;

import lombok.Data;

@Data
public class StudentWithLambok {
	
	private int rollno;
	private String name;
	private String position;

}

Check the @Data annotation, which combines the features of @ToString, @EqualsAndHashCode, @Getter, @Setter, @AllArgsConstructor, and @NoArgsConstructor. Update the code in the spring boot main class as follows.


package com.onlyxcodes.lambokapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.onlyxcodes.lambokapp.model.StudentBuilderClassLevel;
import com.onlyxcodes.lambokapp.model.StudentBuilderConstructorLevel;
import com.onlyxcodes.lambokapp.model.StudentBuilderMethodLevel;
import com.onlyxcodes.lambokapp.model.StudentWithLambok;

import lombok.AllArgsConstructor;

@SpringBootApplication
public class LambokSpringBootDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(LambokSpringBootDemoApplication.class, args);
		
		System.out.println();
		System.out.println("------------------------- test @Data annotation method covered all @Getter, @Setter, @ToString, etc---------------------------------");
		
		
		StudentWithLambok lambokDataGetterSetter = new StudentWithLambok();
		
		lambokDataGetterSetter.setRollno(50);
		lambokDataGetterSetter.setName("Hamid");
		lambokDataGetterSetter.setPosition("Programmer");
		
		System.out.println(lambokDataGetterSetter.getRollno());
		System.out.println(lambokDataGetterSetter.getName());
		System.out.println(lambokDataGetterSetter.getPosition()); 
		
		System.out.println();
		System.out.println("--------------------- @Data output covered @ToString method -------------------------------------");
		System.out.println();
		
		StudentWithLambok lambokDataToString = new StudentWithLambok();
		
		lambokDataToString.setRollno(50);
		lambokDataToString.setName("Hamid");
		lambokDataToString.setPosition("Programmer");
		
		System.out.println(lambokDataToString.toString());
		
		System.out.println();
		System.out.println("--------------------- @Data output covered @NoArgsConstructor method -------------------------------------");
		
		StudentWithLambok lambokDataNoArgumentConstructor = new StudentWithLambok();
		
		System.out.println(lambokDataNoArgumentConstructor.getRollno());
		System.out.println(lambokDataNoArgumentConstructor.getName());
		System.out.println(lambokDataNoArgumentConstructor.getPosition()); 
		
		System.out.println();
		System.out.println("--------------------- @Data output covered @AllArgsConstructor method -------------------------------------");
		System.out.println();
		
		StudentWithLambok lambokDataArgumentConstructor = new StudentWithLambok(52, "Hamid", "Programmer");
		System.out.println(lambokDataArgumentConstructor.toString()); 
		
		System.out.println();
		System.out.println("--------------------- @Data output covered @Equal method -------------------------------------");
		
		StudentWithLambok lambokDataTest1 = new StudentWithLambok();
		
		lambokDataTest1.setRollno(50);
		lambokDataTest1.setName("Hamid");
		lambokDataTest1.setPosition("Programmer");
		
		StudentWithLambok lambokDataTest2 = new StudentWithLambok();
		
		lambokDataTest2.setRollno(50);
		lambokDataTest2.setName("Hamid");
		lambokDataTest2.setPosition("Programmer");
		
		System.out.println(lambokDataTest1.equals(lambokDataTest2));
		
		System.out.println();
		System.out.println("--------------------- @Data output covered @EqualsAndHashCode method -------------------------------------");
		
		System.out.println(lambokDataTest1.hashCode());
		System.out.println(lambokDataTest2.hashCode()); 
		
	}
}

This indicates that the @Data annotation can generate comparable objects (@EqualsAndHashCode), classes with necessary fields in constructors (@AllArgsConstructor), the @ToString method of a class for all fields, and @Getters and @Setters for you.


Output of lambok data annotation.


@data annotation output

Friends Here,


I put all of the spring main class codes together so that you can easily check all of the annotation output in your spring boot apache tomcat server's console.


package com.onlyxcodes.lambokapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.onlyxcodes.lambokapp.model.StudentBuilderClassLevel;
import com.onlyxcodes.lambokapp.model.StudentBuilderConstructorLevel;
import com.onlyxcodes.lambokapp.model.StudentBuilderMethodLevel;
import com.onlyxcodes.lambokapp.model.StudentWithLambok;

import lombok.AllArgsConstructor;

@SpringBootApplication
public class LambokSpringBootDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(LambokSpringBootDemoApplication.class, args);
		
		System.out.println();
		System.out.println("------------------------- test @Setter and @Getter annotation method ---------------------------------");
		
		StudentWithLambok lambokGS = new StudentWithLambok();
		
		//test getter and setter methods
		lambokGS.setRollno(50);
		lambokGS.setName("Hamid");
		lambokGS.setPosition("Programmer");
		
		System.out.println(lambokGS.getRollno());
		System.out.println(lambokGS.getName());
		System.out.println(lambokGS.getPosition()); 
		
		System.out.println();
		System.out.println("------------------------- test @toString annotation method ---------------------------------");
		System.out.println(); 
		
		//test toString method
		StudentWithLambok lamboktoString = new StudentWithLambok();
		
		lamboktoString.setRollno(50);
		lamboktoString.setName("Hamid");
		lamboktoString.setPosition("Programmer");
		
		System.out.println(lamboktoString.toString()); 
		
		System.out.println();
		System.out.println("------------------------- test @NoArgsConstructor annotation method ---------------------------------");
		
		//test @NoArgsConstructor 
		StudentWithLambok lambokNoArgumentConstructor = new StudentWithLambok();
		System.out.println(lambokNoArgumentConstructor.getRollno());
		System.out.println(lambokNoArgumentConstructor.getName());
		System.out.println(lambokNoArgumentConstructor.getPosition()); 
		
		System.out.println();
		System.out.println("------------------------- test @AllArgsConstructor annotation method ---------------------------------");
		System.out.println();
		
		//test @AllArgsConstructor constructor
		StudentWithLambok lambokArgumentConstructor = new StudentWithLambok(52, "Hamid", "Programmer");
		System.out.println(lambokArgumentConstructor.toString()); 
		
		System.out.println();
		System.out.println("------------------------- test @Equals annotation method ---------------------------------");
		
		//test equals method
		StudentWithLambok lambokTest1 = new StudentWithLambok();
		
		lambokTest1.setRollno(50);
		lambokTest1.setName("Hamid");
		lambokTest1.setPosition("Programmer");
		
		StudentWithLambok lambokTest2 = new StudentWithLambok();
		
		lambokTest2.setRollno(50);
		lambokTest2.setName("Hamid");
		lambokTest2.setPosition("Programmer");
		
		System.out.println(lambokTest1.equals(lambokTest2));
		
		System.out.println();
		System.out.println("------------------------- test @EqualsAndHashCode annotation method ---------------------------------");
		
		//test EqualAndHasCode method
		System.out.println(lambokTest1.hashCode());
		System.out.println(lambokTest2.hashCode()); 
		
		System.out.println();
		System.out.println("------------------------- test @Builder annotation using class level ---------------------------------");
		
		
		//test builder method
		StudentBuilderClassLevel lambokBuilderClassLevel = StudentBuilderClassLevel.builder()
				.rollno(40)
				.name("hamid")
				.position("programmer")
				.build();
		
		System.out.println("rollno => "+lambokBuilderClassLevel.getRollno());
		System.out.println("name => "+lambokBuilderClassLevel.getName());
		System.out.println("position => "+lambokBuilderClassLevel.getPosition()); 
		
		
		System.out.println();
		System.out.println("------------------------- test @Builder annotation using constructor level ---------------------------------");
		
		
		StudentBuilderConstructorLevel lambokBuilderConstructorLevel = StudentBuilderConstructorLevel.builder()
				.rollno(10)
				.name("hamid")
				.position("designer")
				.build();
		
		System.out.println("rollno => "+lambokBuilderConstructorLevel.getRollno());
		System.out.println("name => "+lambokBuilderConstructorLevel.getName());
		System.out.println("position => "+lambokBuilderConstructorLevel.getPosition()); 
		
		System.out.println();
		System.out.println("------------------------- test @Builder annotation using method level ---------------------------------");
		
		
		StudentBuilderMethodLevel lambokBuilderMethodLevel = StudentBuilderMethodLevel.builder()
				.rollno(25)
				.name("hamid")
				.position("designer")
				.build();
		
		System.out.println("rollno => "+lambokBuilderMethodLevel.getRollno());
		System.out.println("name => "+lambokBuilderMethodLevel.getName());
		System.out.println("position => "+lambokBuilderMethodLevel.getPosition());
		System.out.println("status => "+lambokBuilderMethodLevel.isStatus()); 
		
		System.out.println();
		System.out.println("------------------------- test @Data annotation method covered all @Getter, @Setter, @ToString, etc---------------------------------");
		
		
		StudentWithLambok lambokDataGetterSetter = new StudentWithLambok();
		
		lambokDataGetterSetter.setRollno(50);
		lambokDataGetterSetter.setName("Hamid");
		lambokDataGetterSetter.setPosition("Programmer");
		
		System.out.println(lambokDataGetterSetter.getRollno());
		System.out.println(lambokDataGetterSetter.getName());
		System.out.println(lambokDataGetterSetter.getPosition()); 
		
		System.out.println();
		System.out.println("--------------------- @Data output covered @ToString method -------------------------------------");
		System.out.println();
		
		StudentWithLambok lambokDataToString = new StudentWithLambok();
		
		lambokDataToString.setRollno(50);
		lambokDataToString.setName("Hamid");
		lambokDataToString.setPosition("Programmer");
		
		System.out.println(lambokDataToString.toString());
		
		System.out.println();
		System.out.println("--------------------- @Data output covered @NoArgsConstructor method -------------------------------------");
		
		StudentWithLambok lambokDataNoArgumentConstructor = new StudentWithLambok();
		
		System.out.println(lambokDataNoArgumentConstructor.getRollno());
		System.out.println(lambokDataNoArgumentConstructor.getName());
		System.out.println(lambokDataNoArgumentConstructor.getPosition()); 
		
		System.out.println();
		System.out.println("--------------------- @Data output covered @AllArgsConstructor method -------------------------------------");
		System.out.println();
		
		StudentWithLambok lambokDataArgumentConstructor = new StudentWithLambok(52, "Hamid", "Programmer");
		System.out.println(lambokDataArgumentConstructor.toString()); 
		
		System.out.println();
		System.out.println("--------------------- @Data output covered @Equal method -------------------------------------");
		
		StudentWithLambok lambokDataTest1 = new StudentWithLambok();
		
		lambokDataTest1.setRollno(50);
		lambokDataTest1.setName("Hamid");
		lambokDataTest1.setPosition("Programmer");
		
		StudentWithLambok lambokDataTest2 = new StudentWithLambok();
		
		lambokDataTest2.setRollno(50);
		lambokDataTest2.setName("Hamid");
		lambokDataTest2.setPosition("Programmer");
		
		System.out.println(lambokDataTest1.equals(lambokDataTest2));
		
		System.out.println();
		System.out.println("--------------------- @Data output covered @EqualsAndHashCode method -------------------------------------");
		
		System.out.println(lambokDataTest1.hashCode());
		System.out.println(lambokDataTest2.hashCode()); 
		
	}
}

Download Codes

No comments:

Post a Comment

Post Bottom Ad