Programming/Spring

(spring) web.xml, root-context.xml, servlet-context.xml 각각의 역할과 차이점

Jan92 2024. 1. 16. 22:44

web.xml, root-context.xml, servlet-context.xml 각각의 역할과 차이점

web.xml root-context.xml servlet-context.xml

최근 선언적 트랜잭션을 사용하기 위한 설정을 하는 과정에서 'root-context.xml' 파일과 'servlet-context.xml' 파일, 'web.xml' 파일의 역할과 차이점에 대한 궁금증이 생겨 정리한 내용입니다.

 

본격적인 내용에 앞서 Spring 프로젝트에서 xml 파일은 1. 애플리케이션 컨텍스트를 설정하는 데 사용되거나, 2. 웹 애플리케이션의 구성을 지정하는 데 사용되는데요.

 

1. 애플리케이션 컨텍스트를 설정하는 xml 파일의 경우에는 빈(Bean)의 생성과 다른 빈에 대한 의존성, AOP 설정, 프로퍼티 설정 등을 포함합니다.

(root-context.xml, servlet-context.xml이 여기에 해당한다고 볼 수 있습니다.)

 

2. 웹 애플리케이션을 구성하는 xml 파일의 경우에는 서블릿 정의, 필터 설정, 리스너 구성 등 웹 애플리케이션의 기본 구성을 정의합니다.

(web.xml 파일이 여기에 해당된다고 볼 수 있습니다.)

 


web.xml 이란? + web.xml 파일의 작동 순서

'web.xml' 파일은 웹 애플리케이션 서버(WAS)가 최초로 구동될 때 읽혀지며, 해당 파일을 통해 웹 애플리케이션 설정을 구성합니다.

이때 web.xml 파일 내에서 여러 xml 파일(root-context.xml, servlet-context.xml 등)을 읽어오도록 설정하고 있으며, 때문에 설정을 위한 설정 파일로 볼 수 있습니다.

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://Java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<!-- 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>

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
		
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>

 (web.xml)

 

이어서 스프링 프로젝트의 기본적인 web.xml 파일과 해당 파일의 작동 순서는 다음과 같습니다.

 

먼저 주석의 내용처럼 <context-param> 부분을 통해 모든 Servlets와 Filters에서 공유될 Spring Container를 정의하는데요.

이때 읽어오는 파일이 바로 root-context.xml입니다.

그리고 <listener> 부분에서 ContextLoaderListener를 통해 root-context.xml에 정의된 Spring Container를 생성합니다.

 

이어서 <servlet> 부분을 통해 DispatcherServlet이 등록되며, 그 과정에서 servlet-context.xml 파일을 읽어 필요한 Spring Container를 생성하게 됩니다.

 

 


servlet-context.xml 이란?

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<context:component-scan base-package="com.example.board" use-default-filters="false"> 
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> 
	</context:component-scan>
	
</beans:beans>

(servlet-context.xml)

 

'servlet-context.xml' 파일은 DispatcherServlet 등록 시 읽어오는 파일입니다.

웹 애플리케이션에서 클라이언트의 요청을 받기 위해 필요한 컨테이너들이 정의되어 있으며 Controller(url과 관련), Annotation, ViewResolver, Interceptor 등의 설정을 가지고 있습니다.

 

***

위 web.xml 파일의 동작 과정에서 본 것처럼 root-context.xml 파일에 설정된 스프링 컨테이너가 등록된 후 DispatcherServlet 등록 시 servlet-context.xml 파일에 설정된 스프링 컨테이너가 등록됩니다.

때문에 servlet-context에서 root-context에 설정된 스프링 컨테이너의 빈을 사용할 수는 있지만, 반대로 root-context에서 servlet-context의 설정 정보를 사용할 수는 없다는 특징이 있습니다.

 

 


root-context.xml 이란?

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
	http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

	<!-- Root Context: defines shared resources visible to all other web components -->

	<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="net.sf.log4jdbc.sql.jdbcapi.DriverSpy" />
		<property name="url" value="jdbc:log4jdbc:mysql://localhost:3306/spring_mvc?serverTimezone=UTC&amp;useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;allowPublicKeyRetrieval=true" />
		<property name="username" value="root" />
		<property name="password" value="" />
	</bean>

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mapperLocations" value="classpath:/mappers/**/*Mapper.xml" />
	</bean>
	
	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg index="0" ref="sqlSessionFactory" />
	</bean>
	
	<context:component-scan base-package="com.example.board">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
	</context:component-scan>
	
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/> 
	</bean>

	<tx:annotation-driven transaction-manager="transactionManager"/>
	
</beans>

(root-context.xml)

 

'root-context.xml' 파일입니다.

Service, Repository(DAO), DB 등의 웹 환경에 독립적인(+ 비즈니스 로직과 관련된) 스프링 컨테이너들이 정의되어 있습니다.

 

WAS 시작 시 root-context에 설정된 스프링 컨테이너가 가장 먼저 등록되기 때문에 해당 파일에 정의된 빈들은 모든 컨텍스트에서 사용할 수 있으며, 서로 다른 servlet-contextx에서 공유해야 하는 빈들 역시 해당 파일에서 등록하여 사용할 수 있습니다.

 

 


mvc-context

이미지 출처: https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-servlet/context-hierarchy.html

마지막으로 스프링 공식 홈페이지의 mvc-context(Servlet WebApplicationContext, Root WebApplicationContext) 관련 이미지입니다.

 

 

 

< 참고 자료 >

https://velog.io/@cheshirehyun/servlet-context.xml-root-context.xml-web.xml
https://linked2ev.github.io/spring/2019/09/15/Spring-5-%EC%84%9C%EB%B8%94%EB%A6%BF%EA%B3%BC-%EC%8A%A4%ED%94%84%EB%A7%81%EC%97%90%EC%84%9C-Context(%EC%BB%A8%ED%85%8D%EC%8A%A4%ED%8A%B8)%EB%9E%80/