This article introduces the blessing of SpringBoot's elegant coded Lombok, and shares it with you, as follows:
Overview
Lombok helps simplify eliminating some java code that must have but seems bloated by providing simple syntax annotations. Typically, the simplification of POJO objects (such as automatically generating Setters and Getters for us, etc.), with the support of Lombok, developers can avoid many repetitive and bloated operations, greatly improving the signal-to-noise ratio of Java code, so we must try and apply it!
Configuration on IntelliJ IDEA
Method 1: Configure directly in the IDEA interface
First enter the Plugins interface:
Then search and install the Lombok plugin:
Finally, don't forget to enable the Enable option of Annotation Processors:
After the above installation is completed, IDEA needs to be restarted to take effect!
Method 2: Manually download the Lombok plug-in installation
Sometimes due to network reasons, the above method fails to install, so you can only manually download and install it.
Download the lombok plugin:
https://github.com/mplushnikov/lombok-intellij-plugin/releases
Plugins -> Install plugin from disk... Select the downloaded zip package installation
Just restart idea
After the settings in the IDE are completed, you need to add the following lombok dependency in pom.xml to use it
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.16</version></dependency>
Lombok main notes
@Getter and @Setter / Automatically provide Set and Get methods for properties@ToString / The function 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 implies, automatically generates constructors with corresponding parameters for the class@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog / Automatically add corresponding log support to the class@Data / Automatically add @ToString, @EqualsAndHashCode, @Getter, add @Setter, and @RequiredArgsConstructor to non-final fields, which is essentially equivalent to the comprehensive effect of several annotations.@NonNull / Automatically helps us avoid null pointers. Annotations acting on method parameters are used to automatically generate null parameter checks@Cleanup / Automatically call the close() method for us. It acts on local variables. When the scope ends, the close method will be automatically called to release resources. Here is a practical code battle with @Data and @Log annotations that are most frequently used in Lombok!
@Data annotation use
The official website’s explanation about @Data annotation is 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 an integration of multiple Lombok annotations, so it is very convenient to use!
First, create a POJO entity UserLombok. The general writing method 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 (!o.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's blessing, the writing method can be simplified to:
@Datapublic class UserLombok { private final String name; private int age; private double score; private String[] tags;}When used in IDEA, Lombok's annotations will be automatically completed, as shown in the following figure:
Let's write the 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:
Results Print
Since Lombok automatically generates 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 practice
In my article Spring Boot Log Framework Practice, we use Log4j2 as a 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"; }}If you use Lombok instead, 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")@Log4j2public 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 about it, is everything so elegant!
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.