The @RequiredArgsConstructor
annotation is a feature of Lombok, a Java library that helps reduce boilerplate code.
When you use
@RequiredArgsConstructor
on a class, Lombok generates a constructor for all fields that are marked asfinal
or are marked with@NonNull
.
This is particularly useful for creating immutable objects or for dependency injection.
Here’s a simple example of how it works:
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public class MyTestClass {
private final String requiredField;
private final int anotherRequiredField;
private String optionalField;
}
In this example, Lombok will generate a constructor like this:
public MyTestClass(String requiredField, int anotherRequiredField) {
this.requiredField = requiredField;
this.anotherRequiredField = anotherRequiredField;
}
The optionalField
is not included in the constructor because it's neither final
nor marked with @NonNull
.
To use Lombok, you need to include it as a dependency in your project and have the Lombok plugin installed in your IDE. For Maven, you would add it to your pom.xml
like this:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.34</version>
<scope>provided</scope>
</dependency>
Lombok can make your code cleaner and easier to maintain by reducing the need for boilerplate code.