@RequiredArgsConstructor(onConstructor = @__(@Inject)

최진규·2023년 5월 15일
0

뒤에 옵션은 왜 사용하는걸까...?

시니어 개발자분이 붙이는걸보고 좀 궁금해서 서치해봤다.

일단 스프링에서는 생성자 주입방식을 많이 사용하는데, (여러가지 이점이 있다.)

@RequiredArgsConstructor는 롬복의 어노테이션인데 해당 어노테이션과 주입받은 빈들을 final로 선언하는 조합으로 생성자 주입방식을 사용한다.

  
@Service  
@RequiredArgsConstructor  
public class RequiredArgsConstructorTestService {  
  
  private final CommonService commonService;  
}

이런 방식이다.

@RequiredArgsConstructor 이 적용되고 나서는 다음과 같이 컴파일 단계에서 코드가 주입된다.

@Service  
public class RequiredArgsConstructorTestService {  
  
  private final CommonService commonService;  
  
  public RequiredArgsConstructorTestService(CommonService commonService) {  
    this.commonService = commonService;  
  }  
}

이렇게...

하지만 onConstructor 사용해보자.

  
@Service  
@RequiredArgsConstructor(onConstructor = @__(@Inject)  
public class RequiredArgsConstructorTestService {  
  
  private final CommonService commonService;  
}

그러면 다음과 같이 컴파일 단계에서 코드가 생성된다.

@Service  
public class RequiredArgsConstructorTestService {  
  
  private final CommonService commonService;  

  @Inject
  public RequiredArgsConstructorTestService(CommonService commonService) {  
    this.commonService = commonService;  
  }  
}

즉 생성자에 옵션으로 준 어노테이션을 달아준다.

그러면 왜 이렇게 하는걸까 ?

바로 생성자가 여러개인 경우를 상정해야 하기 때문이다.

스프링 의존성 주입은 @Inject또는 @Autowired 등의 어노테이션이 붙은 생성자를 기본 사용한다.
만약 생성자가 한개라면 어노테이션이 없어도 사용한다.
하지만 생성자가 여러개라면 어노테이션이 붙은 생성자를 사용하게 된다.

profile
개발하는 개복치

0개의 댓글