왜 ‘생성자’를 통해서 @Autowired 의존성을 주입받을까? field나 setter도 있잖아!!
라고 생각이 들어 이 포스팅을 작성하게 되었다.
근데 setter는 public 으로 구현할 수밖에 없다.
그렇기 때문에 언제 어디서든 덮어쓰기가 가능하다!!!
해당 문제점을 느끼고 개발자들은 또다른 니즈를 찾게 되었다.
그럼 스프링이 넣어준 걸 쓰고 싶다! 한 번 주입받은 객체는 변하지 말아야 한다
그래서 field가 등장!!!
field는 놀랍게도 불변성이다!
@Service
class TripService {
@Autowired
private TripRepository tripResitory;
}
@Component
ATripRepository implements TripRepository
BTripRepository implements TripRepository
이 코드의 테스트 코드를 생각해보자
class Test {
@Test
public void tripServiceTest(){
TripService tripService = new TripService(); // 필드는 ATripRepository 으로 initialize됨 => 얘만 컴포넌트여서
// 만약, BTripRepo로 필드 주입하고 싶다면, @Component를 B로 바꿔줘야함.
}
}
필드에 의존성을 주입하면, 개발자가 코드를 수정하는 것이 아니라
스프링 어노테이션을 바꿔서 수정하는 일이 생겨버림
⇒ 즉, 너무 불변이다!!!!
A로 주입하고 싶다면
생성자 주입은
객체 생성 전에는 생성할 수 있고, 그 이후에는 불변하다
위 코드의 문제점은 아래처럼 해결할 수 있다~
class Test {
@Test
public void tripServiceTest(){
// A를 넣고 싶다면
ATripRepository aTripRepository = new ATripRepository();
TripService tripService = new TripService(aTripRepository);
// B를 넣고 싶다면
BTripRepository bTripRepository = new BTripRepository();
TripService tripService = new TripService(bTripRepository);
}
}
생성자는 가변과 불변 그 사이에 있다.
해당 문제는 의존성을 주입하는 시점 때문에 발생한다.!!