1. Brief description
Lombok is a commonly used tool library in Java development. It greatly simplifies code development through annotation, especially in common scenarios such as Getter/Setter, construction methods, log tools, etc., which can greatly reduce boilerplate code. This article will provide an in-depth explanation of Lombok's usage tips and precautions from basic introduction to advanced usage.
2. What is Lombok
Lombok is a Java annotation processing tool that automatically generates code through compile-time annotations. By adding short annotations to the code, Lombok can automatically generate common methods for classes, thereby reducing redundant code and improving development efficiency.
Main functions
- Automatically generate Getter/Setter.
- Generate equals, hashCode, toString.
- Automatic generation of constructors.
- Supports Builder mode.
- Integrated logging tools.
- Provides advanced features such as chain calls, custom access levels, etc.
2.1 Maven dependencies
Introducing Lombok in the project:
<dependency> <groupId></groupId> <artifactId>lombok</artifactId> <version>1.18.30</version> <scope>provided</scope> </dependency>
Note: provided means that Lombok is only valid at compile time and does not need to rely on it at runtime.
2.2 IDE configuration
Most IDEs (such as IntelliJ IDEA, Eclipse) support Lombok, but plug-ins are required:
IntelliJ IDEA: Search Lombok in the plugin market and install it.
Eclipse: Download and install the Lombok jar file, run java -jar for configuration.
3. Basic usage
3.1 Automatically generate Getters and Setters
Lombok's @Getter and @Setter annotations automatically generate getXXX and setXXX methods for the field of the class.
import ; import ; public class User { @Getter @Setter private String name; @Getter @Setter private int age; }
After use, the compiler will automatically generate the following code:
public String getName() { return name; } public void setName(String name) { = name; } public int getAge() { return age; } public void setAge(int age) { = age; }
3.2 Constructor Annotation
- @NoArgsConstructor: Generate parameterless constructor.
- @AllArgsConstructor: Generate a constructor containing all fields.
- @RequiredArgsConstructor: Generate a constructor containing the final field.
import ; import ; import ; @NoArgsConstructor @AllArgsConstructor @RequiredArgsConstructor public class User { private final String id; private String name; private int age; }
3.3 @ToString and @EqualsAndHashCode
@ToString: Generates a toString method that automatically contains fields in the class.
@EqualsAndHashCode: Generate equals and hashCode methods.
import ; import ; @ToString @EqualsAndHashCode public class User { private String name; private int age; }
3.4 @Data annotation
@Data is a combination annotation, equivalent to a collection of the following annotations:
- @Getter
- @Setter
- @ToString
- @EqualsAndHashCode
- @RequiredArgsConstructor
import ; @Data public class User { private String name; private int age; }
4. Advanced usage
4.1 Builder mode
Lombok provides @Builder annotation to automatically generate code for Builder mode, suitable for scenarios where complex objects are needed.
import ; import ; @Builder @ToString public class User { private String name; private int age; private String address; }
How to use:
User user = () .name("John") .age(30) .address("New York") .build(); (user);
4.2 Log annotation
Lombok provides a variety of log annotations, automatically injecting corresponding log tools into classes:
@Slf4j: Inject SLF4J log object.
@Log4j2: Inject Log4j2 log object.
@CommonsLog: Inject Commons Logging log object.
import .slf4j.Slf4j; @Slf4j public class LoggingExample { public static void main(String[] args) { ("This is an info log."); ("This is an error log."); } }
4.3 Chain call
The Setter method of chain calls can be generated through @Accessors(fluent = true, chain = true).
import ; import ; import ; @Getter @Setter @Accessors(chain = true) public class User { private String name; private int age; }
How to use:
User user = new User().setName("John").setAge(30); (());
4.4 Customize the access levels of Getter and Setter
Access levels (such as PUBLIC, PRIVATE) can be set through the AccessLevel properties of @Getter and @Setter.
import ; import ; import ; public class User { @Getter @Setter() private String name; }
4.5 @Value: Immutable Object
The @Value annotation marks the class as an immutable object, which is equivalent to:
- All fields are private final.
- Class is final.
- Automatically generate Getters.
import ; @Value public class ImmutableUser { String name; int age; }
4.6 @SneakyThrows: Exception handling
@SneakyThrows annotation will automatically wrap the checked exception as a runtime exception.
import ; public class SneakyThrowsExample { @SneakyThrows public void readFile() { throw new Exception("Checked Exception"); } }
4.7 Experimental function: @With
The @With annotation can be used to generate copy methods for immutable objects, which replace certain fields.
import ; import ; @Value public class User { @With private String name; private int age; }
How to use:
User user1 = new User("John", 30); User user2 = ("Doe"); (user1); // User(name=John, age=30) (user2); // User(name=Doe, age=30)
5. Summary
Lombok is a magic tool to simplify boilerplate code in Java development. Its annotations such as @Getter, @Setter, @Builder, etc. can significantly improve coding efficiency. In addition, advanced features like @Value and @With provide convenience for building immutable objects.
In daily development, the rational use of Lombok not only makes the code more concise and elegant, but also improves the team's development efficiency. However, in some key scenarios where code logic needs to be clarified, it is still necessary to use it with caution to avoid readability issues.
This is the end of this article about the technical guide for the use of Lombok tool library in Java. For more related Java Lombok library content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!