Example of how Spring Boot USES Lombok to reduce boilerplate code in Java

  • 2020-10-31 21:45:13
  • OfStack

preface

What Lombok wants to solve is that a large number of Getter/Setter methods in our entity Bean, as well as toString, hashCode and other methods may not be used, but sometimes still need to be copied in order to make it easy to use. After using Lombok, it will automatically generate code for you, note that it will automatically generate code for you while you are running. That is, it will greatly reduce the amount of code you have.

Lombok official address: https:// ES14en. org/

To be honest, The first time I heard of Lombok, I learned it from an old Hungarian teacher who taught me. At that point he gave me a set of JPA code to access the database. When I opened the code, I saw a full screen of errors. I opened the entity Entity class 1 and saw that there were no methods for setter and getter, just the definition of some member variables. I was a mess. What the hell. Then he told me to look up lombok.

In fact, for Java, Love and hate have always been intertwined. On the one hand, Java is a very mature programming language, and many open source frameworks and libraries make it relatively easy to develop. On the other hand, it can be very verbose because of the amount of boilerplate code that needs to be written in general. Although the introduction of Lambdas and stream in Java8 has made things a little bit better, there are still some differences in some areas, such as writing simple Java objects Pojo, but now with Lombok you can see how easy it is to write code. Because a lot of common methods like Setter, getter, toString, equal, and even constructors have done it for you, all we need to do is add annotations to the right places.

The methods are as follows:

First let's look at how the traditional Java POJO class should be defined:


public class User {

 private String name;
 private String surname;
 private int age;

 public User(String name, String surname, int age) {
  this.name = name;
  this.surname = surname;
  this.age = age;
 }

 public String getName() {
  return name;
 }

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

 public String getSurname() {
  return surname;
 }

 public void setSurname(String surname) {
  this.surname = surname;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 @Override
 public boolean equals(Object o) {
  if (this == o) return true;
  if (o == null || getClass() != o.getClass()) return false;
  User user = (User) o;
  return age == user.age
    && Objects.equals(name, user.name)
    && Objects.equals(surname, user.surname);
 }

 @Override
 public int hashCode() {
  return Objects.hash(name, surname, age);
 }

 @Override
 public String toString() {
  return "User{" +
    "name='" + name + '\'' +
    ", surname='" + surname + '\'' +
    ", age=" + age +
    '}';
 }

}

There are only three member fields in this regular POJO class, name, surname, and age. But it has the 1-cut common elements of the common POJO class: getters,** setters, equals, hashCode, and toString** methods.

To complete this class with only three member variables, we actually wrote diamante on almost 60 lines. Sure, IDE will help you automatically generate some method implementations if you use IDE, but don't you get a headache when you read the code? Let's simplify our code by using Lombok.

Start by adding Lombok dependencies to your project:


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

In general, if you use IDE such as Intellji and Eclipse, you will need to install Plugin of Lombok to use it correctly. Lombok provides 1 basic annotations to member variables to ensure that each member variable automatically has access to methods.


@EqualsAndHashCode
@ToString
@AllArgsConstructor
public class User {

 @Setter
 @Getter
 private String name;

 @Setter
 @Getter
 private String surname;

 @Setter
 @Getter
 private int age;

}

As you can see, we used five basic annotations.

@EqualsAndHashCode, @ToString tells Lombok to generate equals, hashCode, and toString methods, and lombok USES all the member variables when generating these methods. @AllArgsConstructor automatically creates a constructor with all its members. The @Getter / @Setter annotations annotation automatically generates a corresponding method for each member variable of the tag.

Now we just need to use it normally like this


User user = new User("John", "Doe", 32);
user.setAge(30);
user.equals(new User("John", "Doe", 30)); // true

If you do not want to use annotations on all member variables, but only on some variables, you can provide a variable that specifies which member variables need to be automatically generated. Here, for example, we don't want the member variable age to appear in the toString method. We can do this:


@EqualsAndHashCode
@ToString(of = {"name", "surname"})
@AllArgsConstructor
public class User {

 @Getter
 @Setter
 private String name;

 @Getter
 @Setter
 private String surname;

 @Getter
 @Setter
 private int age;

}

When I think about it, this code is much better than what we started with 1, but it's still not neat enough. Numerous @Getter and @ES105en annotations are repeated here. Using Class is convenient if you just want to expose a few fields, but it becomes annoying and boring if you need to generate accessors for all the fields. To make the code cleaner, Lombok perpetuity we use these annotations at the class level. If these annotations are placed above the class name, lombok will automatically generate access methods for all fields for us.


@EqualsAndHashCode
@ToString
@AllArgsConstructor
@Getter
@Setter
public class User {

 private String name;
 private String surname;
 private int age;

}

The changes we've made so far haven't changed the behavior of our classes, but they've made our classes look cleaner. This is what we want to achieve with Lombok.

Lombok also has an annotation called @Builder. Let's look at a piece of code that looks like this:


@EqualsAndHashCode
@ToString
@AllArgsConstructor
@Getter
@Setter
@Builder
public class User {

 private String name;
 private String surname;
 private int age;

}

We have added an @Builder annotation to the User class. If we want to instantiate this class, is the first thing you think of?


User user=new User;
user.setxxx();
....
....

But now we can use the @Builder annotation to generate instances like this:


User user = User.builder()
  .name("John")
  .surname("Doe")
  .age(32)
  .build();

How about, isn't it convenient for you to generate instances when setter doesn't have to be written.

Having said that, the following annotation is the essence of Lombok:

Simply put, all of the annotations we can do with 1 annotation. For him it's the @Data annotation.


@Data
@Builder
public class User {

 private String name;
 private String surname;
 private int age;

}

We only need to add one @Data annotation to define the class. We don't need to add any other annotation to achieve all the functions mentioned above. If you don't believe it, you can try it

conclusion


Related articles: