BackEnd/Spring

[Spring] ERROR: org.springframework.web.servlet.DispatcherServlet - Context initialization failed

코딩마루 2023. 5. 14. 21:21

1. 문제 상황

"ERROR: org.springframework.web.servlet.DispatcherServlet - Context initialization failed"는 스프링 설정 파일 구성 문제로 인해 발생하는 에러다. 내 경우 tomcat 실행 후 spring 컨테이너가 처음 구동될 때 해당 문제가 발생했다.

2. 해결 방법

내 경우 web.xml에 applicationContext.xml 파일의 설정이 잘 되어있지 않아 발생했다. 수정한 web.xml은 아래와 같이 applicationContext.xml 파일과 dispatcher-servlet.xml 파일 두 스프링 설정 파일에 대한 경로를 잘 설정하고 있다. (즉, 내 경우 applicationContext.xml의 경로를 추가하지 않아 발생한 문제다.)  

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

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!--applicationContext.xml 설정-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/config/applicationContext.xml</param-value>
  </context-param>
  
  <!--Encoding 설정-->
  <filter>
    <filter-name>characterEncoding</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>
  </filter>
  <filter-mapping>
    <filter-name>characterEncoding</filter-name>
    <url-pattern>*.do</url-pattern>
  </filter-mapping> 
  
  <!--dispatcher-servlet.xml 설정-->
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/config/dispatcher-servlet.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

추가적으로 annotation 사용을 위해 applicationContext.xml에서는 @controller를 제외한 어노테이션을, dispacher-servlet.xml에서는 @controller만을 스캔하도록 설정했다. 먼저 applicationContext.xml에서 해당 내용은 아래와 같다.

<!--applicationContext.xml-->
<!--(생략)-->
<context:component-scan base-package="com.greenmate">
    <context:exclude-filter type="annotation"
                            expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!--(생략)-->

dispacher-servlet.xml의 해당 내용은 아래와 같다. 

<!--dispatcher-servlet.xml-->
<!--(생략)-->
<context:component-scan base-package="com.greenmate">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!--(생략)-->