EN
Lombok - most popular usage combinations of Lombok annotations on DTO objects in java
11
points
Using with DTO object
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.FieldDefaults;
@Data
@NoArgsConstructor
@AllArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
public class AddPostRequest {
String postName;
String postBody;
}
Why to use @NoArgsConstructor
?
We can use this DTO with json libraries that requires empty constructor. All fiels will be private and we have all args contructor annotation if we want to create object in this way.
Lombok - private final fields
Below we can see how to make all fields 'private final' using Lombok annotations. It is quite simple, we just use:
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
Complete example:
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.experimental.FieldDefaults;
@Data
@AllArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
public class AddPostRequest {
String postName;
String postBody;
}
Notes
Default values in @FieldDefaults annotation:
- By default access level is set to: NONE
- By default make fianl is set to: false
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface FieldDefaults {
AccessLevel level() default AccessLevel.NONE;
boolean makeFinal() default false;
}
Handle exceptions with lombok
- SneakyThrows at projectlombok.org
import lombok.SneakyThrows;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class AfterParseDataExample {
public static void main(String[] args) {
List<String> csvLines = readCsvFile(Paths.get("some/path/to/csv"));
System.out.println(csvLines);
}
@SneakyThrows(IOException.class)
public static List<String> readCsvFile(Path absolutePath) {
return Files.readAllLines(absolutePath);
}
}
Private constructors
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
public class LombokPrivateConstructorExample {
@NoArgsConstructor(access = AccessLevel.PRIVATE)
private static class User {
}
@AllArgsConstructor(access = AccessLevel.PRIVATE)
private static class SuperUser {
}
}
Using with Hibernate entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
@Entity
@Table(name = "posts")
public class PostsEntity {
@Id
@GeneratedValue
Long id;
String title;
// ..
}
Lombok with logger - Slf4j
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class LombokWithLogger {
public static void main(String[] args) {
log.info("Log info");
log.error("Log error");
// internally it uses:
// org.slf4j
}
}