Spring

[Spring] STS web.xml root-context.xml servlet-context.xml설정

안녕고래 2023. 10. 9. 01:20

web.xml은 DD (Deployment Descriptor : 배포 설명자)라고 불리며, Web Application의 설정파일이다.

DD는 Web Application 실행 시 메모리에 로드된다.

즉, web.xml이란 웹 어플리케이션을 실행시킬 때 함께 올라가야할 설정(설명)들을 정의해놓은 것이다.

 

0. 톰캣 서버(WAS)를 처음 구동하면 어플리케이션이 실행되고 WAS에 의해 web.xml이 loading 된다.

1. web.xml파일을 로딩하여 서블릿 컨테이너가 구동된다.

2. 서블릿 컨테이너는 web.xml 파일에 등록된 ContextLoaderListener 객체를 생성(Pre- Loading)한다.

3. ContextLoaderListener 객체는 root-context.xml 파일을 로딩하여 스프링 컨테이너를 구동하는데 이를 'Root Container라고 한다. (WEB-INF/spring/root-context.xml 또는 src/main/resources/applicationContext.xml )

Service class, Dao class 등 객체들이 메모리에 생성 (@Service, @Repository, @Component  URL과 상관이 없는 객체 component-scan) root-context.xml에는 주로 view 지원을 제외한 공통 bean을 설정한다. (web과 관련된 bean들은 등록해주지 않음) 예시로 spring properties 파일을 로컬과 서버용으로 구분지을 때 여기서 property value를 설정해준다.(databaseDataSource, repository 설정을 주로함)

4. client로 부터 최초로 웹 어플리케이션 요청이오면 서블릿 컨테이너는DispatcherServlet 객체를 생성하고 

servlet-context.xml 파일을 로딩하여 두번째 스프링 컨테이너를 구동한다. ( /WEB-INF/spring/appServlet/ 또는 WEB-INF/config/) 이 두 번째 스프링 컨테이너가 Controller 객체를 메모리에 생성한다. DispatcherServlet은 FrontController의 역할을 수행한다. 클라이언트로부터 요청 온 메시지를 분석하여 알맞은 PageController에게 전달하고 응답을 받아 요청에 따른 응답을 어떻게 할지 결정한다.

 

web.xml

	<!-- The definition of the Root Spring Container shared by all Servlets 
		and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>

	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener>
	...

 

servlet-context.xml

	...

	<annotation-driven /> --어노테이션을 사용함을 선언

	...
	
	<!-- URL과 상관이 있는 객체 base-package로 설정된 위치의 아래 찾아보기 -->
	<context:component-scan base-package="com.spring.byewhale" />

 

톰캣(was)구동 -> 어플리케이션 실행 -> was가 web.xml loading -> 서블릿 컨테이너가 구동 -> ContextLoaderListener (Pre- Loading) 객체 생성 -> root-context.xml 파일 로딩 -> 스프링 컨테이너(Root Container) 구동 -> Service, Dao 객체 생성 -> client 요청 -> DispatcherServlet 객체 생성 servlet-context.xml 파일을 로딩 -> 두번째 스프링 컨테이너 구동 -> Controller 객체를 메모리에 생성

 

 

 

출처 : https://javannspring.tistory.com/231

ContextLoaderListener와 DispatcherServlet이 각각 XmlWebApplicationContext를 생성함.

ContextLoaderListener 가 생성하는 컨테이터를 Root컨테이너(부모컨테이너라고 생각하면 쉽다)이고 DispatcherServlet이 생성한 컨테이너는 자식 컨테이너가 된다. 부모 컨테이너가 생성한 비즈니스 객체를 자식 컨테이너가 생성한 Controller에서 참조하여 사용할 수 있다.

 

 

[참고]

https://javannspring.tistory.com/231

 

Spring Framework 실행순서

사전지식POJO스프링의 특징 중 하나평범한 옛날 자바 객체Not POJO = Servlet의 특징javax.servlet, javax.servlet.http 패키지를 import해야 한다.Servlet, Generic Servlet, HttpServlet 중 하나를 상속해야 한다.생명주기

javannspring.tistory.com

■ 책 스프링 퀵 스타트