SpringBoot elegant coding: Lombok blessing

Xiaomi game book


Overview

Lombok helps simplify and eliminate some must-have but bloated java code by providing a simple form of syntax annotations. Typical is the simplification of POJO objects (such as automatically generating Setters and Getters for us, etc.), with the blessing of Lombok, developers can avoid a lot of repetitive and bloated operations, greatly improving the signal-to-noise ratio of java code , so we Must try and apply!


Configuration on IntelliJ IDEA

Method 1: Configure directly in the IDEA interface

  • First enter the Plugins interface:

Enter the Plugins interface

  • Then search for and install the Lombok plugin:

Install the Lombok plugin

  • Finally, don't forget to turn on the Enable option of Annotation Processors:

Enable Annotation Processors

After the above installation is complete, you need to restart IDEA to take effect!


Method 2: Manually download the Lombok plugin and install it

Sometimes due to network reasons, the above method one fails to install in this way, so you can only download and install manually

Select lombok's zip package to install

  • Just restart the idea

Restart IDEA to take effect

After setting in IDE, you need to add the following lombok dependency in pom.xml to use

<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
	<version>1.16.16</version>
</dependency>

Lombok main annotations

  • @Getter and @Setter/ Automatically provide Set and Get methods for properties
  • @ToString/ The role of this annotation is to automatically generate the toString() method for the class
  • @EqualsAndHashCode/ Automatically generate hashCode and equals implementations for object fields
  • @AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor/ As the name suggests, the constructor that automatically generates the corresponding parameters for the class
  • @Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog/ Automatically add the corresponding log support for the class
  • @Data/ Automatically add @ToString , @EqualsAndHashCode, @Getter for all fields, @Setter , and @RequiredArgsConstructor for non-final fields, which are essentially equivalent to the combined effect of several annotations
  • @NonNull/ automatically helps us avoid null pointers. Annotation acting on method parameters to automatically generate null parameter checks
  • @Cleanup/ Automatically call the close() method for us. Acting on local variables, when the scope ends, the close method is automatically called to release resources

The following is a code combat with the most frequently used annotations in @DataLombok !@Log


Use the @Data annotation

The official website explains the @Data annotation as follows:

All together now: A shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, @Setter on all non-final fields, and @RequiredArgsConstructor!

It is not difficult to understand, it can be regarded as the integration of multiple Lombok annotations, so it is very convenient to use!

  • Let's first create a POJO entity UserLombok, the common way of writing is as follows:
public class UserLombok {
  private final String name;
  private int age;
  private double score;
  private String[] tags;
  
  public UserLombok(String name) {
    this.name = name;
  }
  
  public String getName() {
    return this.name;
  }
  
  void setAge(int age) {
    this.age = age;
  }
  
  public int getAge() {
    return this.age;
  }
  
  public void setScore(double score) {
    this.score = score;
  }
  
  public double getScore() {
    return this.score;
  }
  
  public String[] getTags() {
    return this.tags;
  }
  
  public void setTags(String[] tags) {
    this.tags = tags;
  }
  
  @Override public String toString() {
    return "DataExample(" + this.getName() + ", " + this.getAge() + ", " + this.getScore() + ", " + Arrays.deepToString(this.getTags()) + “)”;
  }
  
  protected boolean canEqual(Object other) {
    return other instanceof DataExample;
  }
  
  @Override public boolean equals(Object o) {
    if (o == this) return true;
    if (!(o instanceof DataExample)) return false;
    DataExample other = (DataExample) o;
    if (!other.canEqual((Object)this)) return false;
    if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName())) return false;
    if (this.getAge() != other.getAge()) return false;
    if (Double.compare(this.getScore(), other.getScore()) != 0) return false;
    if (!Arrays.deepEquals(this.getTags(), other.getTags())) return false;
    return true;
  }
  
  @Override public int hashCode() {
    final int PRIME = 59;
    int result = 1;
    final long temp1 = Double.doubleToLongBits(this.getScore());
    result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode());
    result = (result*PRIME) + this.getAge();
    result = (result*PRIME) + (int)(temp1 ^ (temp1 >>> 32));
    result = (result*PRIME) + Arrays.deepHashCode(this.getTags());
    return result;
  }
}
  • After Lombok blessing, the writing can be simplified as:
@Data
public class UserLombok {
    private final String name;
    private int age;
    private double score;
    private String[] tags;
}

When used in IDEA, Lombok's annotations are automatically completed, as shown in the following figure:

Lombok annotation autocompletion

  • Let's write POJO test code
    public static void main( String[] args ) {
        UserLombok userLombok = new UserLombok("hansonwang99”);
        userLombok.setAge(18);
        String[] array = new String[]{"apple","juice”};
        userLombok.setTags( array );
        userLombok.setScore( 99.0 );
        System.out.println(userLombok);
    }

From the figure below, we can see that IDEA can still automatically complete the code automatically generated by Lombok for us:

auto-generated code

  • result print

Since Lombok automatically generated the toString method for us, the print result of the object is as follows:

UserLombok(name=hansonwang99, age=18, score=99.0, tags=[apple, juice])

@Log annotation in action

In my article Spring Boot Logging Framework Practice , we use Log4j2 as the log object, which is written as follows:

@RestController
@RequestMapping("/testlogging”)
public class LoggingTestController {

    private final Logger logger = LogManager.getLogger(this.getClass());

    @GetMapping("/hello”)
    public String hello() {
        for(int i=0;i<10_0000;i++){
            logger.info("info execute index method”);
            logger.warn("warn execute index method”);
            logger.error("error execute index method”);

        }

        return "My First SpringBoot Application”;
    }
}

After switching to Lombok, the writing method becomes more concise, we only need to introduce the corresponding @Log annotation to complete the generation of the log object:

@RestController
@RequestMapping("/testloggingwithlombok”)
@Log4j2
public class LoggingTestControllerLombok {

    @GetMapping("/hello”)
    public String hello() {
        for(int i=0;i<10_0000;i++){
            log.info("info execute index method”);
            log.warn("warn execute index method”);
            log.error("error execute index method”);

        }

        return "My First SpringBoot Application”;
    }
}

How, isn't everything so elegant!


postscript

The author's more SpringBt practice articles are here:


CodeSheep

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324399056&siteId=291194637