Say “bye bye!!!” to Annoying Getters/Setters & Shorten your Java Code with ` lombok `
-
Still, there are things that a Java programmer has to do over and over again just to get the code complete from language/syntax point-of-view rather than spending time on business logic, the actual task at hand. Having to write or even auto-generate Getters ,Setters, custom Constructors and custom toString method in POJOs is one such issue. As a solution for this cumbersome problem, Project Lombok has quite elegantly addressed this issue.First, just need to add the lombok dependency to your project and then use the available annotations appropriately. In your Spring boot project, go to pom.xml file and add the below dependency within the tags <dependencies>...</dependencies>
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> <version>1.18.8</version> </dependency>
Check for the most recent available version here.
For the latest lombok.jar file
1.0 Annotations Available for Use
Lombok project provides us with several annotations to avoid boilerplate codes in our entity class. Given below is a list of the available annotations and some very essential set of the annotations will be discussed briefly with examples.
*Annotation List*
@Getter @Setter @Builder @NonNull
@Data @ToString @Getter(lazy=true) @AllArgsConstructor
@NonNull @EqualsAndHashCode
@NoArgsConstructor @Value @Log @Synchronized
@RequiredArgsConstructor @SneakyThrows @Cleanup
@ToString.Exclude @ToString.Include
@EqualsAndHashCode.Exclude=========================================================================
@Getter/@Setter
When you annotate your Entity class with @Getter and @Setter , it will generate getter methods and setter methods for all the fields in your class.
Or, you can place these two annotations separately before the necessary fields (Not before the class name) ,when you don't need getting and setting methods for all the fields available.
@NoArgsConstructor
When you place this constructor before the class name, this will create a constructor without any arguments in it.(an empty constructor)
This annotation is useful primarily in combination with either @Data or one of the other constructor generating annotations.
@AllArgsConstructor
This annotation when place before the class name, generates a constructor taking all the fields as arguments in it.
@NonNull
You can use @NonNull on the parameter of a method or constructor to have lombok generate a null-check statement for you.(See below code examples)
** Using @NonNull annotation **
package com.udith.articles.lombokDemo.entities; import com.udith.articles.lombokDemo.entities.Person; import java.io.Serializable; import lombok.NonNull; public class Student extends Serializable { private String name; public Student(@NonNull Person person) { super("Hello"); this.name = person.getName(); } }
** When lombok generates the code for the above snippet, the code looks like this **
package com.udith.articles.lombokDemo.entities; import com.udith.articles.lombokDemo.entities.Person; import java.io.Serializable; import lombok.NonNull; public class Student extends Serializable { private String name; public Student(@NonNull Person person) { super("Hello"); if (person == null) { throw new NullPointerException("person is marked @NonNull but is null"); } this.name = person.getName(); } }
Further, you can annotate the fields in an entity class so that those marked fields will be used for creating constructor with the annotations @Data and @RequiredArgsConstructor .
@RequiredArgsConstructor
@RequiredArgsConstructor generates a constructor with parameters for the fields that requires special handling. All non-initialized final fields get a parameter, as well as any fields that are marked as @NonNull that aren't initialized where they are declared.
See the code snippet below. The commented part shows the lombok generated constructor.
When this annotation generates the constructor, the parameters included are ordered in the way the corresponding fields are ordered.
@ToString
This is also a very useful annotation in debugging etc. Any class definition may be annotated with @ToString to let lombok generate an implementation of the toString() method. By default, it'll print your class name, along with each field, in order, separated by commas.
@ToString annotation by default implies @ToString(includeFieldNames = true) .But, by changing its above property to false, a string without fields' names can be returned.
Further, we can customize the fields that we need to exclude and include to the ToString() method. This can be achieved in two ways.
1) Use of @ToString.Exclude annotation with @ToString annotation.
Just add @ToString.Exclude annotation before the fields that you need to exclude from the returned string. (See the example right).
2) Use of @ToString.Include annotation with @ToString(onlyExplicitlyIncluded = true) annotation.
After adding @ToString(onlyExplicitlyIncluded = true) before the class, add @ToString.Include before the required fields. Then, only those required fields will be included in the returned string.
@EqualsAndHashCode
When placed before a class declaration , this annotation implements public boolean equals(Object obj){} method for all the fields and public int hashCode(){} method for all the fields.
You can exclude any field that needn't to be inserted in the generated two methods, simply by placing @EqualsAndHashCode.Exclude annotation over the field you need to exclude.
[ Or, you can explicitly include the required fields for these two methods by replacing @EqualsAndHashCode with ** @EqualsAndHashCode(onlyExplicitlyIncluded = true) ** before the class declaration and then placing @EqualsAndHashCode.Include over the required fields. ]
@Data
This is a very convenient shortcut key that bundles the features of @ToString, @EqualsAndHashCode, @Getter / @Setter and @RequiredArgsConstructor together.
package com.udith.lombokdemo.entities; import java.io.Serializable; import java.util.Date; import java.util.Objects; import javax.persistence.Entity; import javax.persistence.Id; import lombok.Data; @Entity @Data public class Student implements Serializable { @Id private long id; private int age; private Date birthday; }
===================*******************************============================
Above explained are only some frequently used annotations, but you can handle them smoother as you require with lombok. You can find more features here.
By,
Udith Indrakantha,
Author of https://webtechmora.blogspot.com -
@Udith-Indrakantha Patta