@RequiredArgsConstructor

Kuno17·2023년 2월 5일

Spring

목록 보기
1/3

RequiredArgsConstructor

@RequiredArgsConstructor는 초기화 되지않은 final 필드나, @NonNull 이 붙은 필드에 대해 생성자를 생성해 줍니다.

새로운 필드를 추가할 때 다시 생성자를 만들어서 관리해야하는 번거로움을 없애준다. (@Autowired를 사용하지 않고 의존성 주입)

@RestController
@RequiredArgsConstructor
@RequestMapping("/example")
public class RequiredArgsConstructorControllerExample {

  private final FirstService firstService;
  private final SecondService secondService;
  private final ThirdService thirdService;
  
  ...
}

만약 @RequiredArgsConstructor를 사용하지 않고 생성자 코드를 모두 작성한 경우?

@RestController
@RequiredArgsConstructor
@RequestMapping("/example")
public class RequiredArgsConstructorControllerExample {

  private final FirstService firstService;
  private final SecondService secondService;
  private final ThirdService thirdService;
  
  @Autowired
  public RequiredArgsConstructorControllerExample(FirstService firstService, SecondService secondService, ThirdService thirdService) {
    this.firstRepository = firstRepository;
    this.secondRepository = secondRepository;
    this.thirdRepository = thirdRepository;
  }
}

많다...정말 편한거다...

profile
자바 스터디 정리 - 하단 홈 버튼 참조.

0개의 댓글