preface
There is a lot of repetitive, similar code in Java applications that barely changes after generation, but we have to spend a lot of effort writing it to meet Java’s compilation requirements
For example, in Java application development, we almost have to add get(),set() and other methods to the member variables of all beans. These relatively fixed but mandatory code wastes a lot of programmer’s energy and makes the class content look more cluttered. We want to focus our limited energy on more important areas.
Lombok has been around for so long that it’s even included in Spring Boot Initalizr,
Here’s Lombok in more detail:
Lombok
Introduction to the official website: Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java. Never write another getter or equals method again. Early access to future java features such as val, and much more.
To put it bluntly: Lombok is a Java™ utility that helps developers eliminate Java verbosity, especially for simple Java objects (POJOs). It does this through annotations, see:
The contrast of the Bean
A traditional POJO class looks like this
The POJO class transformed by Lombok looks like this
As you can see ata glance, when we wrote the Employee class we implemented the get() and set() methods for all member variables with the @data annotation, and the Employee class looked much cleaner. The magic of Lombok is not limited to the rich annotations that meet most of our development needs.
The installation of Lombok
Looking at the @data implementation below, we see that this annotation is applied at compile time
This is very different from most of the annotations we use, such as Spring’s annotations (which implement business logic at run time through reflection), such as Spring’s @RestController annotation
A more straightforward example of this is that most ides automatically recognize the syntax of a package after it is referenced. However, Lombok’s annotations are not automatically recognized by most ides. Therefore, to use Lombok, you need to install plug-ins to support IDE compilation. To prevent IDE automatic check error, the following uses IntelliJ IDEA as an example to install the plug-in.
Search Lombok in Repositories, install and restart the IDE
Add dependencies to a Maven or Gradle project
At this point we can do something with the annotations provided by Lombok.
Full explanation of Lombok
Lombok offers a lot of annotations, but don’t drink too much of them. Here are some of the annotations Lombok recommends using (some of which are not very different from Java writing, such as @synchronized)
@ Getter and @ Setter
This annotation can be applied to class or member variables. As expected, @getter and @setter automatically generate get and set methods for member variables. By default, the generated access is public.
The member variable name specifies that the set method is generated with protected access; The Boolean member variable female generates only get methods and changes the method name to isFemale(). When this annotation is applied to a class, get and set methods are generated for all non-static member variables by default, or can be manually disabled with accessLevel. NONE, as shown below:
@ToString
The annotation needs to be applied to the class to generate the toString method of Object. Several attributes in the annotation can enrich the content we want. The exclude attribute prohibits the use of a field in the toString method, while the of attribute specifies the field to be used, as shown in the following figure:
Looking at the compiled employee.class shows what we expect, as shown below
@EqualsAndHashCode
This annotation needs to be applied to the class. Lombok generates equals(Object Other) and HashCode () methods for us, including all non-static and non-transient attributes. The annotation can also exclude certain fields by using the exclude attribute. The of attribute specifies certain fields. We can also use the superclass fields in overridden methods using the callSuper attribute. This gives us more flexibility in defining bean alignments, as shown in the following figure:
Look at the compiled employee.class file as shown below:
@NonNull
This annotation must be applied to the arguments or attributes of a method or constructor to determine the validity of the arguments. NullPointerException is thrown by default
Looking at the nonnullexample. class file, it throws a null pointer exception for us, as shown below:
Of course we can throw other exceptions by specifying the exception type, Lombok. NonNull. ExceptionType = [NullPointerException | IllegalArgumentException], in order to achieve this function we need in the root directory of the project lombok. The new config file:
Recompiling the NonNullExample class already throws an invalid parameter exception for us:
@NoArgsConstructor, @RequiredArgsConstructor, @AllArgsConstructor
The above three annotations generate a no-argument constructor for us, specify a parameter constructor, and a constructor that contains all parameters. By default, The constructor generated by @requiredargsconstructor does non-null validation for all attributes marked @nonnull.
The no-parameter constructor is easy to understand, and we’ll focus on the latter two, starting with @requiredargsconstructor
As you can see from the above figure, the @requiredargsConstructor annotation generates a parameter constructor that contains only fields with final and @nonNULL identifiers, and we can specify staticName to construct objects by generating static methods
Look at the employee.class file
When we remove the staticName attribute we look at the following file:
I’m sure you’ve noticed the details
@allargsconstructor is simpler, please check it out for yourself
@Data
Now that I’ve introduced the annotation above, it’s pretty easy to follow the @data annotation, which applies to classes, Is a combination of @toString, @equalSandhashCode, @getter / @setter, and @requiredargsConstructor, as shown below:
@Builder
Functional programming, or streaming operations, is becoming more popular in most languages to make programs simpler, more readable, and more coherent. @Builder brings this functionality, generating a set of Builder apis. This annotation also needs to be applied to classes, as shown in the examples below.
The compiled employee.class file looks like this:
Mom no longer need to worry about my set value so troublesome, streaming operation done:
@Log
This annotation needs to be applied to the class. In writing the service layer, we need to add some logs to locate problems. We usually define a static constant Logger and apply it where we want to log.
Look at the class file, as we expected:
There are many variants of Log, CommonLog, Log4j, Log4j2, Slf4j, etc. Lombok is still well supported with variant annotations:
I actually use the @slf4J annotation
val
For those of you familiar with Javascript, var can define any type of variable, whereas in Java we need to specify the type of a specific variable. Val lets us get rid of that, and when compiled, matches exactly the type, which is final by default, just like the functional expressions in Java8. () – > System. Out. Println (” hello lombok “); You can parse to the Runnable functional interface.
@Cleanup
When operating on a stream, we usually need to call a close method to close or end a resource. The @cleanup annotation helps us to call a close method and place it ina try/finally block, as shown below:
The compiled class file looks like this, and we find ourselves surrounded by try/finally and calling the close method of the stream
Try-with-resource has been available since JDK1.7, so we don’t have to explicitly close streams
conclusion
Lombok’s basic workflow looks like this:
- Define compile-time annotations
- Create compile-time Annotation handlers using the JSR269 API (Pluggable Annotation Processing API)
- Using the JavAC API of Tools.jar to handle AST(Abstract Syntax Tree)
- Register functionality into the JAR package
Lombok also has a lot of annotations, but I recommend using the above. It’s a convenience tool, not a binding one. Lombok allows me to focus on effective code and eliminate the “get, set, etc.” code that makes little sense. Lombok-generated code can also be as easy to use as utility classes (@Builder).
For more information, please visit www.projectlombok.org/
Soul asking
- Why only one
@EqualsAndHashCode
Comments? Rather than@Equals
和@HashCode
? There is a specification involved - If all three constructor modes are applied simultaneously, this is added
@Builder
Notes, what happens? - Are your lights still on?
- Java upgrade so fast, how to flexibly switch and manage multiple versions?
- Guide you to customize the standard Spring Boot starter
- EasyExcel is easy and flexible to read Excel content
Welcome to continue to pay attention to the public account: “One soldier of The Japanese Arch”
- Cutting-edge Java technology dry goods sharing
- Efficient tool summary | back “tool”
- Interview question analysis and solution
- Technical data to receive reply | “data”
To read detective novel thinking easy fun learning Java technology stack related knowledge, in line with the simplification of complex problems, abstract problems concrete and graphical principles of gradual decomposition of technical problems, technology continues to update, please continue to pay attention to……