Lombokμλ μμ±μ κ΄λ ¨ μ΄λ
Έν
μ΄μ
μ΄ λνμ μΌλ‘ 3κ°μ§κ° μλ€.
@NoArgsConstructor
@AllArgsConstructor
@RequiredArgsConstructor
κ°κ°μ λν΄ λͺ
ννκ² μμ보μ!
첫 λ²μ§Έλ‘ @NoArgsConstructor μ΄λ
Έν
μ΄μ
μ κ²½μ° λ§€κ°λ³μκ° μλ κΈ°λ³Έ μμ±μλ₯Ό λ§λ€μ΄ μ€λ€.
μλ₯Ό λ€μ΄ μ΄λ° ν΄λμ€κ° μμ λ
@NoArgsConstructor
public class Post {
private Long id;
private String title;
private String content;
private LocalDateTime createdAt;
}
Lombokμ λ΄λΆμ μΌλ‘ μλμ κ°μ΄ κΈ°λ³Έ μμ±μλ₯Ό λ§λ€μ΄μ€λ€.
public Post() {}
JPA κ°μ νλ μμν¬λ Jackson κ°μ λΌμ΄λΈλ¬λ¦¬λ₯Ό μ¬μ©νλ €λ©΄ κΈ°λ³Έ μμ±μκ° μ¬μ€μ νμμ΄κΈ° λλ¬Έμ μμ£Ό μ μ©νκ² μ¬μ©λλ€.
@AllArgsConstructorλ μ΄λ¦μμλ μ μ μλ―μ΄ λͺ¨λ νλλ₯Ό λ§€κ°λ³μλ‘ λ°λ μμ±μλ₯Ό μλμΌλ‘ λ§λ€μ΄μ€λ€.
@AllArgsConstructor
public class Post {
private Long id;
private String title;
private String content;
private LocalDateTime createdAt;
}
μμ κ°μ ν΄λμ€κ° μμ λ λ΄λΆμ μΌλ‘ μλμ κ°μ μμ±μλ₯Ό λ§λ λ€.
public Post(Long id, String title, String content, LocalDateTime createdAt) {
this.id = id;
this.title = title;
this.content = content;
this.createdAt = createdAt;
}
DTOμ κ°μ΄ λͺ¨λ νλκ°μ μ΄κΈ°νν΄μΌ νλ κ²½μ°λ Builder ν¨ν΄μ μ¬μ©νλ κ²½μ° μ μ©νλ€.
λ§μ§λ§μΌλ‘ @RequiredArgsConstructorλ final ν€μλ λλ @NonNullμ΄ λΆμ νλλ§ ν¬ν¨νλ μμ±μλ₯Ό λ§λ€μ΄μ€λ€.
@RequiredArgsConstructor
public class PostService {
private final PostRepository postRepository;
}
μμ κ°μ μ½λμ λ΄λΆμ μΌλ‘ μλμ μμ±μλ₯Ό λ§λ€μ΄μ€λ€.
public class PostService {
private final PostRepository postRepository;
public PostService(PostRepository postRepository) {
this.postRepository = postRepository;
}
}
μ£Όλ‘ Springμμ μμ±μ κΈ°λ° μμ‘΄μ± μ£Όμ (DI)μ ν λ μμ£Ό μ¬μ©λλ€.
* μΆκ°μ μΌλ‘ μμ 3κ°μ§ μ΄λ Έν μ΄μ μ κ²½μ° νμλ μλμ§λ§ μ¬μ© κ°λ₯ν 4κ°μ§ μ΅μ λ€μ΄ μλ€.
@AllArgsConstructor(staticName = "of")
public class Post {
private Long id;
private String title;
private String content;
private LocalDateTime createdAt;
}
// μλμ κ°μ μ μ λ©μλκ° μλμΌλ‘ μμ±λλ€.
public static Post of(Long id, String title, String content, LocalDateTime createdAt) {
return new Post(id, title, content, createdAt);
}
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PostService {
private final PostRepository postRepository;
}
// μλμ ννλ‘ μμ±μλ₯Ό λ§λ€μ΄μ€λ€.
@Autowired
public PostService(PostRepository postRepository) {
this.postRepository = postRepository;
}
