title: How to correctly load context in Spring using web.xml and Tomcat
body: <p>i have a problem importing a Spring context in my servlet class. The methods are working fine in test (with context loaded). But i seem to be incapable of loading the context in my webapp. I'm using Tomcat 7. Here is my <code>web.xml</code> file:</p>
  
  <pre><code> &lt;?xml version="1.0" encoding="UTF-8"?&gt;
   &lt;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" id="WebApp_ID" version="2.5"&gt;
   &lt;display-name&gt;AgneseProva&lt;/display-name&gt;
   &lt;context-param&gt;
      &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
      &lt;param-value&gt;
          /WEB-INF/spring/app-config.xml
      &lt;/param-value&gt;
   &lt;/context-param&gt;
   &lt;listener&gt;
      &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
   &lt;/listener&gt;
   &lt;servlet&gt; 
   &lt;description&gt;&lt;/description&gt;
   &lt;display-name&gt;Prova&lt;/display-name&gt;
   &lt;servlet-name&gt;Prova&lt;/servlet-name&gt;
   &lt;servlet-class&gt;it.jenia.agnese.prova.Prova&lt;/servlet-class&gt;
   &lt;/servlet&gt;
   &lt;servlet&gt;
   &lt;description&gt;&lt;/description&gt;
   &lt;display-name&gt;Presenze&lt;/display-name&gt;
   &lt;servlet-name&gt;Presenze&lt;/servlet-name&gt;
   &lt;servlet-class&gt;it.jenia.agnese.prova.Presenze&lt;/servlet-class&gt;
   &lt;/servlet&gt;
   &lt;servlet-mapping&gt;
   &lt;servlet-name&gt;Prova&lt;/servlet-name&gt;
   &lt;url-pattern&gt;/Prova&lt;/url-pattern&gt;
   &lt;/servlet-mapping&gt;
   &lt;servlet-mapping&gt;
   &lt;servlet-name&gt;Presenze&lt;/servlet-name&gt;
   &lt;url-pattern&gt;/Presenze&lt;/url-pattern&gt;
   &lt;/servlet-mapping&gt;
   &lt;/web-app&gt;
  </code></pre>
  
  <p>This is my application context <code>app-config.xml</code>:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:context="http://www.springframework.org/schema/context"
     xmlns:tx="http://www.springframework.org/schema/tx"
     xsi:schemaLocation="
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"&gt;
     &lt;context:annotation-config /&gt;
      &lt;import resource="classpath*:/test-prova-spring-configuration.xml" /&gt; 
   &lt;/beans&gt;
  </code></pre>
  
  <p>The file test-prova-spring-configuration.xml contains a series of import with the database configuration, the repository configuration, the entities and the services.</p>
  
  <p>The Servlet class is:</p>
  
  <pre><code> package it.jenia.agnese.prova;
  
   import it.jenia.ac.mail.rapportini.repository.CollaboratoreRepository;
   import it.jenia.ac.mail.rapportini.repository.PresenzaRepository;
   import it.jenia.vr.common.service.JspReporter;
  
   import java.io.IOException;
  
   import javax.servlet.ServletException;
   import javax.servlet.http.HttpServlet;
   import javax.servlet.http.HttpServletRequest;
   import javax.servlet.http.HttpServletResponse;
  
   import org.apache.log4j.Logger;
   import org.springframework.beans.factory.annotation.Autowired;
  
   public class Presenze extends HttpServlet {
   private static final long serialVersionUID = 1L;
   private static Logger logger = Logger.getLogger(Presenze.class);
  
   @Autowired
   CollaboratoreRepository collaboratoreRepository;
   @Autowired
   PresenzaRepository presenzaRepository;
   @Autowired
   JspReporter jsp;
  
   public Presenze() {
       super();
   }
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      String messaggiojsp = "ok";
      String messaggiopr = "ok";
      String messaggiocr = "ok";
      if (jsp==null){
          messaggiojsp = "ko";
      }
      request.setAttribute("messaggiojsp", messaggiojsp);
      if(presenzaRepository ==null){
          messaggiopr = "ko";
      }
      request.setAttribute("messaggiopr", messaggiopr);
      if(collaboratoreRepository==null){
          messaggiocr = "ko";
      }
      request.setAttribute("messaggiocr", messaggiocr);
      request.getRequestDispatcher("/Presenze/presenze.jsp").forward(request, response);
   }
   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      // TODO Auto-generated method stub
   }
  
   }
  </code></pre>
  
  <p>The server doesn't throw any error, just like if the context was completely loaded, but the autowired fields are null in the servlet. So far i've tried:</p>
  
  <p>1.Registering the servlet as a service with the @Service annotation and adding it's package to the component scan in the spring configuration file (test-prova-spring-configuration.xml)--> nothing changed, fields are null and Tomcat didn't trow any error.</p>
  
  <p>2.Registering the servlet as a bean in the spring configuration file --> nothing changed, fields are null and Tomcat didn't trow any error.</p>
  
  <p>3.Adding those three lines of code to the servlet:</p>
  
  <pre><code>public void init(javax.servlet.ServletConfig config) throws ServletException {
      SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
  };
  </code></pre>
  
  <p>--> the pages throw an error (finally):</p>
  
  <p>org.springframework.beans.factory.BeanCreationException: Injection of autowired dependencies failed for class [class it.jenia.agnese.prova.Presenze];</p>
  
  <p>Traceback:</p>
  
  <pre><code>    exception
  
  javax.servlet.ServletException: Servlet.init() for servlet Presenze threw exception
      org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
      org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
      org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
      org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
      org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
      org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
      org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
      java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
      java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
      org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
      java.lang.Thread.run(Thread.java:745)
  
  root cause
  
  org.springframework.beans.factory.BeanCreationException: Injection of autowired dependencies failed for class [class it.jenia.agnese.prova.Presenze]; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: it.jenia.ac.mail.rapportini.repository.CollaboratoreRepository it.jenia.agnese.prova.Presenze.collaboratoreRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [it.jenia.ac.mail.rapportini.repository.CollaboratoreRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
      org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.processInjection(AutowiredAnnotationBeanPostProcessor.java:306)
      org.springframework.web.context.support.SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(SpringBeanAutowiringSupport.java:110)
      it.jenia.agnese.prova.Presenze.init(Presenze.java:45)
      org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
      org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
      org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
      org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
      org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
      org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
      org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
      java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
      java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
      org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
      java.lang.Thread.run(Thread.java:745)
  
  root cause
  
  org.springframework.beans.factory.BeanCreationException: Could not autowire field: it.jenia.ac.mail.rapportini.repository.CollaboratoreRepository it.jenia.agnese.prova.Presenze.collaboratoreRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [it.jenia.ac.mail.rapportini.repository.CollaboratoreRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
      org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
      org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
      org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.processInjection(AutowiredAnnotationBeanPostProcessor.java:303)
      org.springframework.web.context.support.SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(SpringBeanAutowiringSupport.java:110)
      it.jenia.agnese.prova.Presenze.init(Presenze.java:45)
      org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
      org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
      org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
      org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
      org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
      org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
      org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
      java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
      java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
      org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
      java.lang.Thread.run(Thread.java:745)
  
  root cause
  
  org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [it.jenia.ac.mail.rapportini.repository.CollaboratoreRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
      org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986)
      org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:856)
      org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768)
      org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
      org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
      org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.processInjection(AutowiredAnnotationBeanPostProcessor.java:303)
      org.springframework.web.context.support.SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(SpringBeanAutowiringSupport.java:110)
      it.jenia.agnese.prova.Presenze.init(Presenze.java:45)
      org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
      org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
      org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
      org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
      org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
      org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
      org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
      java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
      java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
      org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
      java.lang.Thread.run(Thread.java:745)
  </code></pre>
  
  <p>However, summarizing, the problem is that it cannot find the beans to autowire the repo in the servlet class.</p>
  
  <p>I sort of finished my "newbie" resources so any help would be much appreciated..</p>
  
  <p>PS. o i forgot I have a maven webapp, the dir structure is:</p>
  
  <pre><code>src
  ---main
  ------java
  ----------it.jenia.agnese.prova
  ---------------Presenze.java
  ------resources
  ------webapp
  ----------META-INF
  --------------test-prova-spring-configuration.xml
  --------------MANIFEST.MF
  ----------WEB-INF
  --------------web.xml
  --------------spring
  ------------------app-config.xml
  ----------Presenze
  --------------presenze.jsp
  </code></pre>