728x90
스프링 DI(Dependency Injection) 방식인 Field 주입, Setter 주입, 생성자(Constructor)주입 중 생성자 주입을 코드 없이 자동으로 설정해주는 애노테이션이다.
@RequiredArgsConstructor는 초기화 되지 않은 final 필드나 @NotNull이 붙은 필드에 대해 생성자를 생성해준다.
기존 생성자 주입
public class SampleController {
private FrstSampleService frstSampleService;
private SecSampleService secSampleService;
@Autowired
public SampleController(FrstSampleService frstSampleService, SecSampleService secSampleService){
this.frstSampleService = frstSampleService;
this.SecSampleService = secSampleService;
}
}
@RequiredArgsConstructor를 이용한 생성자 주입
@RequiredArgsConstructor
public class SampleController {
private final FrstSampleService frstSampleService;
private final SecSampleService secSampleService;
}
@RequiredArgsConstructor를 사용하면, 기존의 생성자 주입 방식을 사용할 때, 새로운 필드 추가 시 다시 생성자를 만들어서 관리해야하는 번거로움을 없애준다. 또한 @Autowired를 사용하지 않고 의존성 주입이 가능해진다.
'스프링' 카테고리의 다른 글
Spring Boot JPA 에서 enum type 사용하기 (0) | 2024.08.26 |
---|---|
스프링5 프로그래밍 입문 - DB 연동 (0) | 2023.11.05 |
스프링5 프로그래밍 입문 - AOP 프로그래밍 (0) | 2023.10.28 |
스프링5 프로그래밍 입문 - 빈 라이프사이클과 범위 (0) | 2023.10.02 |
스프링5 프로그래밍 입문 - 컴포넌트 스캔 (0) | 2023.10.02 |