getBean()의 인자로 인터페이스를 넣어주는 이유

리팩토링 벨로그·2022년 9월 30일
0

다음과 같이 Coach interface in getBean()으로 구체화 하는 이유

Coach theCoach = context.getBean("myCoach", Coach.class);

답변) 인터페이스에서 메서드로 pass 시, 스프링은 객체를 형 변환 해준다.

context.getBean("myCoach", Coach.class)

getBean()의 인자로 Coach 인터페이스를 넣어주는 이유

From the Spring docs:
Behaves the same as getBean(String), but provides a measure of type safety by throwing a BeanNotOfRequiredTypeException if the bean is not of the required type. This means that ClassCastException can't be thrown on casting the result correctly, as can happen with getBean(String).

그런데 일반적인 형 변환과 다른 점이 있다.
getBean(String)과 비슷하게 행동하지만,
요구하는 타입이 아니면 BeanNotOfRequiredTypeException을 던짐으로써 타입 안전 측도를 제공한다. getBean(String)을 쓰면, 형 변환이 잘 되기 위해 ClassCastException이 일어나지 않는다.

하이라이팅 한 부분 해석 애매해서 질문해야 된다.

profile
글 다시 씁니다.

0개의 댓글