웹/Spring

spring web.xml에 대해 분석

jjunbbang 2021. 2. 17. 19:33

먼저 글을 읽기전에 context의 종류를 알아보자.

 

  • context의 종류
    • applicationcontext 
      • 스프링에서 생성한 인터페이스로 어플리케이션의 context를 가지고 있고
      • Web application에 최상단에 위치하고있는 context이다.
      • ioc 컨테이너로써 빈을 만들어주고 관리하고 의존성 주입을 하는 컨테이너로 Beanfactory 인터페이스 또한 상속받는다.
    • webapplicationcontext
      •  applicationcontext를 확장한 인터페이스로 getServletContext와 같이 웹 어플리케이션에 필요한 기능들을 추가한 인터페이스이다.
    • servletcontext
      • Servlet API에서 제공하는 context로 모든 servlet이 공유하는 context이다.
      • Spring Web MVC에선 ServletContext가 Webapplication들을 포함하고 있다. 아래 그림과 같이 Root Application context, servlet application context는 webapplicationcontext이다.

https://stackoverflow.com/questions/33163441/spring-why-root-application-context-and-servlet-application-context-are-cre

Servlet WebApplicationContext

  • Dispatcher servlet에 생성되는 자식 WebApplicationcontext이다.
  • Root webApplicationcontext을 상속 받으며 참조가 가능하지만 그 반대의 경우 Root Webapplication ->servlet Webapplicatiocontextn을 참조하는 것은 불가능하다.
  • 만약 찾고자 하는 빈이 없으면 Root WebApplicationcontext에 접근해 빈을 찾는다.
  • 보통 서블릿을 구성하는데 필요한 Bean을 설정한다 (Controller, Intecpeter, MappingHandler, ViewResolver)

Root WebApplicationContext

  • 어플리케이션에서 하나만 존재하고 최상위 context이다.
  • 여러 servlet에 공유할 수 있는 bean들을 설정하는 곳이다. ->@Repository, @service 등등 

기존에 프로젝트를 진행하던 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/mybatis-context.xml</param-value>
	</context-param>
	

ContextLoaderListener를 통해 생성된 Root Webapplication으로써 모든 서블릿에 공유하고 빈들을 관리하는 설정을 할때 사용한다. 본 설정에선 mybatis-context.xml을 Root Webapplicationcontext로 지정했다.

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

ContextLoaderListener -> Root Webapplicationcontext를 생성.

<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
        <!-- DispatcherServlet생성시 설정 파일을 읽음. -->
			<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>

 

DispatcherServlet은 servlet webApplicationcontext를 생성.

 

스프링에서 servlet이 올라가는 과정.

  • 웹서버가 시작된다 -> Apache Tomcat 내 서블릿 컨테이너는 Servlet Context를 한번 생성해 서버에 메모리를 올린다. 여기서 web.xml에서의 설정은 Spring WebApplicationContext들을 구성하는 작업이다.

[REFERENCES]

docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ApplicationContext.html

live-everyday.tistory.com/164