EN
Lombok - most popular usage combinations of Lombok annotations on DTO objects in java
11 points
xxxxxxxxxx
1
import lombok.AccessLevel;
2
import lombok.AllArgsConstructor;
3
import lombok.Data;
4
import lombok.NoArgsConstructor;
5
import lombok.experimental.FieldDefaults;
6
7
8
9
10
level = AccessLevel.PRIVATE) (
11
public class AddPostRequest {
12
String postName;
13
String postBody;
14
}
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.
Below we can see how to make all fields 'private final' using Lombok annotations. It is quite simple, we just use:
xxxxxxxxxx
1
level = AccessLevel.PRIVATE, makeFinal = true) (
Complete example:
xxxxxxxxxx
1
import lombok.AccessLevel;
2
import lombok.AllArgsConstructor;
3
import lombok.Data;
4
import lombok.experimental.FieldDefaults;
5
6
7
8
level = AccessLevel.PRIVATE, makeFinal = true) (
9
public class AddPostRequest {
10
String postName;
11
String postBody;
12
}
Notes
Default values in @FieldDefaults annotation:
- By default access level is set to: NONE
- By default make fianl is set to: false
xxxxxxxxxx
1
ElementType.TYPE) (
2
RetentionPolicy.SOURCE) (
3
public @interface FieldDefaults {
4
AccessLevel level() default AccessLevel.NONE;
5
boolean makeFinal() default false;
6
}
- SneakyThrows at projectlombok.org
xxxxxxxxxx
1
import lombok.SneakyThrows;
2
3
import java.io.IOException;
4
import java.nio.file.Files;
5
import java.nio.file.Path;
6
import java.nio.file.Paths;
7
import java.util.List;
8
9
public class AfterParseDataExample {
10
11
public static void main(String[] args) {
12
List<String> csvLines = readCsvFile(Paths.get("some/path/to/csv"));
13
System.out.println(csvLines);
14
}
15
16
IOException.class) (
17
public static List<String> readCsvFile(Path absolutePath) {
18
return Files.readAllLines(absolutePath);
19
}
20
}
xxxxxxxxxx
1
import lombok.AccessLevel;
2
import lombok.AllArgsConstructor;
3
import lombok.NoArgsConstructor;
4
5
public class LombokPrivateConstructorExample {
6
7
access = AccessLevel.PRIVATE) (
8
private static class User {
9
10
}
11
12
access = AccessLevel.PRIVATE) (
13
private static class SuperUser {
14
15
}
16
}
xxxxxxxxxx
1
2
3
4
level = AccessLevel.PRIVATE) (
5
6
name = "posts") (
7
public class PostsEntity {
8
9
10
11
Long id;
12
String title;
13
// ..
14
}
xxxxxxxxxx
1
import lombok.extern.slf4j.Slf4j;
2
3
4
public class LombokWithLogger {
5
6
public static void main(String[] args) {
7
log.info("Log info");
8
log.error("Log error");
9
10
// internally it uses:
11
// org.slf4j
12
}
13
}