• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    해결됨

ApplicationContext 계층구조에서 빈 참조 문의드립니다.

21.01.19 02:47 작성 조회수 169

0

안녕하세요.

강의를 따라해보던 중 ApplicationContext를 계층구조로 구성(.xml)하였고 아래와 같이 빈 등록을 해주었습니다.

1) rootWebApplicationContext.xml 

<bean id="helloService" class="..."/>

2) servletWebApplicationContext.xml

<bean id="helloController" class="..."/>

그런데 컨트롤러에서 서비스를 @Autowired로 주입하고 실행하니 서비스 빈이 없다고 NullPointerException 이 발생하였습니다.

그래서 컨트롤러 생성자에서 서비스를 주입받는 형식으로 수정하고 자식 개념의 servletWebApplicationContext.xml에서 아래와 같이 수정하였더니 정상 동작하였습니다.

1) servletWebApplicationContext.xml

<bean id="helloController" class="...">

  <contsructor-arg ref="helloService"/>

</bean>

Servelet WebApplicationContext에서는 Root WebApplicationContext 빈을 참조할 수 있고,

@Autowired 는 constructor-arg...를 대체하는 것으로 알고 있는데 왜 안됐던걸까요?

ps. 알려주신 것처럼 component-scan 설정 시 exclude-filter, include-filter 으로 하면 역시 잘 됩니다. (.xml 기반)

개념이 많이 부족하여 기초적인 질문드립니다.

답변 부탁드립니다. ㅠㅠ

답변 2

·

답변을 작성해보세요.

2

스프링 XML 설정을 쓰면서 @Autowired가 동작하게 하려면 XML에 별도로 설정해 줘야 하는게 있어요.
<context:component-scan base-package="org.example"/> 이런식으로요.

0

Joey님의 프로필

Joey

질문자

2021.01.19

기초 학습이 부족했습니다. 답변 감사드립니다!