StackStalk
  • Home
  • Java
    • Java Collection
    • Spring Boot Collection
  • Python
    • Python Collection
  • C++
    • C++ Collection
    • Progamming Problems
    • Algorithms
    • Data Structures
    • Design Patterns
  • General
    • Tips and Tricks

Wednesday, January 12, 2022

Introduction to Project Lombok

 January 12, 2022     Java     No comments   

Project Lombok

Project Lombok aims to reduce the boilerplate code in Java applications. These include getters, setters, toString, Null checks etc. Project Lombok provides a useful set of annotations for eliminating boilerplate code from Java classes. This makes the code concise and easy to maintain. Project Lombok integrates into the IDE and build process and generates byte code based on the annotations specified. 

Reference: http://projectlombok.org 

As an example, adding a @Data annotation to the insurance info data class below will automatically generate number of new methods in the IDE. This avoids the boilerplate code we would otherwise be writing.


Project Lombok Installation

Steps to install Project Lombok in IDE. Tried on STS “Spring Tools 4 for Eclipse” and it seems to work without issues.
  1. Download Project Lombok as a jar here
  2. Launch Jar file from the command line "java -jar Lombok.jar"
  3. Installer will discover the IDEs installed. If not listed, use the specify location to identify the IDE.
  4. Perform Install/ Update to complete the installation
  5. Restart the IDE
  6. To setup Lombok with any build tool, dependency needs to be specified to specify the source code. For Maven include the Lombok dependency to the pom.xml as below.
  7. <dependency>
    	<groupId>org.projectlombok</groupId>
    	<artifactId>lombok</artifactId>
    	<version>1.18.22</version>
    	<scope>provided</scope>
    </dependency>
    

Project Lombok Annotations

This sections lists some of the common Lombok annotations with examples.

@Getter and @Setter

Purpose: Annotate any field to let Lombok generate the default getter/ setter automatically.
Example: In this insurance info class, we add the annotations on specific fields for generating getter/ setter methods.
package com.stackstalk;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;

public class InsuranceInfo {

	@Getter @Setter private String type;
	@Getter @Setter private Integer premium;
	@Getter @Setter private Integer sumInsured;
	@Getter @Setter(AccessLevel.PROTECTED) private String claimProcess;
}

@ToString

Purpose: Any class definition may be annotated with @ToString to let lombok generate an implementation of the toString() method.
Example: In this insurance info class, we add the @ToString annotation to the class definition to generate toString method.
package com.stackstalk;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@ToString
public class InsuranceInfo {

	@Getter @Setter private String type;
	@Getter @Setter private Integer premium;
	@Getter @Setter private Integer sumInsured;
	@Getter @Setter(AccessLevel.PROTECTED) private String claimProcess;
}

@EqualsAndHashCode

Purpose: Any class definition may be annotated with @EqualsAndHashCode to let lombok generate implementations of the equals(Object other) and hashCode() methods.
Example: In this insurance info class, we add the @EqualsAndHashCode annotation to the class definition to generate hashCode and equals methods.
package com.stackstalk;

import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@ToString
@EqualsAndHashCode
public class InsuranceInfo {

	@Getter @Setter private String type;
	@Getter @Setter private Integer premium;
	@Getter @Setter private Integer sumInsured;
	@Getter @Setter(AccessLevel.PROTECTED) private String claimProcess;
}

@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor

Purpose: Generates constructors that take no arguments, one argument per final / non-null field, or one argument for every field.
Example: In this insurance info class, we add the @AllArgsConstructor annotation to the class definition to generate constructors.
package com.stackstalk;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@ToString
@EqualsAndHashCode
@AllArgsConstructor
public class InsuranceInfo {

	@Getter @Setter private String type;
	@Getter @Setter private Integer premium;
	@Getter @Setter private Integer sumInsured;
	@Getter @Setter(AccessLevel.PROTECTED) private String claimProcess;
}

@Data

Purpose: @Data is a convenient shortcut annotation that bundles the features of @ToString, @EqualsAndHashCode, @Getter / @Setter and @RequiredArgsConstructor together.
Example: In this insurance info class, we add the @Data annotation to the class definition to generate boilerplate code that is normally associated with simple POJOs.
package com.stackstalk;

import lombok.Data;

@Data
public class InsuranceInfo {

	private String type;
	private Integer premium;
	private Integer sumInsured;
	private String claimProcess;
}

@NotNull

Purpose: @NonNull will cause lombok generate a null-check statement.
Example: In this example we add @NonNull to method parameter which generates a null check.
import lombok.Data;
import lombok.NonNull;

public class NonNullTest {

	@Data
	class Employee {
		private Integer empId;
		private String empName;
	}
	
	public static void mymethod(@NonNull Employee employee) {
		System.out.println(employee.getEmpName());
	}
	
	public static void main(String[] args) {
		Employee employee = null;
		mymethod(employee);
	}
}

Output:
Exception in thread "main" java.lang.NullPointerException: employee is marked non-null but is null
	at com.stackstalk.NonNullTest.mymethod(NonNullTest.java:14)
	at com.stackstalk.NonNullTest.main(NonNullTest.java:20)

@Cleanup

Purpose: @Cleanup can be used to ensure a given resource is automatically cleaned up before the code execution path exits the current scope.
Example: In this example, if @Cleanup annotation is removed it would be a resource leak.
package com.stackstalk;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

import lombok.Cleanup;

public class CleanupTest {
	
	public static void main(String[] args) throws IOException {
		InputStream fis = new FileInputStream("/tmp/input.txt");
		InputStreamReader reader = new InputStreamReader(fis, StandardCharsets.UTF_8);
		@Cleanup Scanner in = new Scanner(reader);
	    while ( in.hasNextLine() ) {
	      System.out.println(in.nextLine());
	    }
	}
	
}

@Log

Purpose: @Log on class initializes a static final log field, which can be used to write log statements. There are multiple variants for different logging frameworks. (@Log4j2, @Sfl4j).
Example: In this example we use the insurance info data class and work with log statements.
package com.stackstalk;

import lombok.extern.java.Log;

@Log
public class DataTest {
	
	public static void main(String[] args) {
		InsuranceInfo insurance1 = new InsuranceInfo("Travel Insurance", 1000, 30000, "Easy");
		System.out.println(insurance1);
		
		InsuranceInfo insurance2 = new InsuranceInfo("Car Insurance", 2000, 50000, "Moderate");
		System.out.println(insurance2);
		
		log.info("Created the insurance types");
		
		if (insurance1 == insurance2 ) 
			System.out.println("Same insurance");
		else {
			System.out.println("Different insurance");
			log.severe("Different insurance");
		}
		
	}
}

Conclusion

In this article we have listed only some common examples. All Lombok features are available in this documentation. Overall project Lombok enables better productivity and makes the code concise and easy to maintain.
  • Share This:  
Newer Post Older Post Home

0 comments:

Post a Comment

Follow @StackStalk
Get new posts by email:
Powered by follow.it

Popular Posts

  • Avro Producer and Consumer with Python using Confluent Kafka
    In this article, we will understand Avro a popular data serialization format in streaming data applications and develop a simple Avro Produc...
  • Monitor Spring Boot App with Micrometer and Prometheus
    Modern distributed applications typically have multiple microservices working together. Ability to monitor and manage aspects like health, m...
  • Server-Sent Events with Spring WebFlux
    In this article we will review the concepts of server-sent events and work on an example using WebFlux. Before getting into this article it ...
  • Implement caching in a Spring Boot microservice using Redis
    In this article we will explore how to use Redis as a data cache for a Spring Boot microservice using PostgreSQL as the database. Idea is to...
  • Python FastAPI microservice with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Spring Boot with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Getting started with Kafka in Python
    This article will provide an overview of Kafka and how to get started with Kafka in Python with a simple example. What is Kafka? ...
  • Getting started in GraphQL with Spring Boot
    In this article we will explore basic concepts on GraphQL and look at how to develop a microservice in Spring Boot with GraphQL support. ...

Copyright © StackStalk