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)์ ํ ๋ ์์ฃผ ์ฌ์ฉ๋๋ค.
Lombok์ ์์ฑ์ ๊ด๋ จ ์ด๋ ธํ ์ด์ ์ ๋ช ๊ฐ์ง ์ต์ ์ ํตํด ์์ฑ์์ ๋์์ ์ถ๊ฐ๋ก ์ค์ ํ ์ ์๋ค.
@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;
}
