개발/Spring
🌱Spring/LOMBOK:: @NOARGSCONSTRUCTOR , @ALLARGSCONSTRUCTOR , @REQUIREDARGSCONSTRUCTOR / DI
hyuunii
2023. 5. 11. 13:58
LOMBOK Constructor Injection
@NoArgsConstructor | 파라미터가 없는 기본 생성자를 생성(기본 생성자) |
@AllArgsConstructor | 모든 필드 값을 파라미터로 받는 생성자를 만듦(모든 필드의 생성자) |
@RequiredArgsConstructor | final이나 @NonNull인 필드 값만 파라미터로 받는 생성자 만듦(필수 생성자) |
@NoArgsConstructor
@NoArgsConstructor
public class BookWithLombok {
private Long id;
private String isbn;
private String name;
private String author;
}
public class BookWithOutLombok {
private Long id;
private String isbn;
private String name;
private String author;
public BookWithOutLombok() {
}
}
@AllArgsConstructor
@AllArgsConstructor
public class BookWithLombok {
private Long id;
private String isbn;
private String name;
private String author;
private boolean useYn;
}
public class BookWithLombok {
private Long id;
private String isbn;
private String name;
private String author;
private boolean useYn;
public BookWithLombok(final Long id, final String isbn, final String name, final String author, final boolean useYn) {
this.id = id;
this.isbn = isbn;
this.name = name;
this.author = author;
this.useYn = useYn;
}
}
@RequiredArgsConstructor
@RequiredArgsConstructor
public class BookWithLombok {
private final Long id;
private final String isbn;
private final String name;
private final String author;
private boolean useYn;
}
public class BookWithLombok {
private final Long id;
private final String isbn;
private final String name;
private final String author;
private boolean useYn;
public BookWithLombok(final Long id, final String isbn, final String name, final String author) {
this.id = id;
this.isbn = isbn;
this.name = name;
this.author = author;
}
}
Usage Example
@NoArgsConstructor
@RequiredArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
@NonNull
private String name;
@NonNull
private String pw;
private int age;
}
User user1 = new User(); // @NoArgsConstructor
User user2 = new User("user2", "1234"); // @RequiredArgsConstructor
User user3 = new User(1L, "user3", "1234", null); // @AllArgsConstructor
LOMBOK DI
롬복 적용 전
import org.springframework.stereotype.Service;
@Service
public class TestService {
private final TestRepository testRepository;
public TestService(TestRepository testRepository) {
this.testRepository = testRepository;
}
}
롬복 적용 후
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class TestService {
private final TestRepository testRepository;
}
Reference
- Constructor Injection:
https://lovethefeel.tistory.com/71