title: Injecting dependency in ServletContextListener
body: <p>I have referred to a <a href="https://stackoverflow.com/questions/4746041/spring-injecting-a-dependency-into-a-servletcontextlistener">very helpful previous post</a> but facing a different issue while injecting a bean in a ServletContextListener</p>
  
  <p><strong>The Listener</strong></p>
  
  <pre><code>    package sapphire.social.connector.listener;
  
  import javax.servlet.ServletContextEvent;
  import javax.servlet.ServletContextListener;
  
  import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
  import org.springframework.web.context.support.WebApplicationContextUtils;
  
  import sapphire.adapter.youtube.YTConnectorMgr;
  import sapphire.social.connector.logger.LogManager;
  
  public class AppServletContextListener implements ServletContextListener {
  
      @Override
      public void contextDestroyed(ServletContextEvent arg0) {
          // TODO Auto-generated method stub
          if (LogManager.isDebugOn()) {
              LogManager
                      .debug("AppServletContextListener ::: contextDestroyed :::");
          }
  
      }
  
      @Override
      public void contextInitialized(ServletContextEvent initializingEvent) {
          // TODO Auto-generated method stub
          if (LogManager.isDebugOn()) {
              LogManager
                      .debug("AppServletContextListener ::: contextInitialized :::");
          }
  
          if (LogManager.isDebugOn()) {
              LogManager
                      .debug("AppServletContextListener ::: contextInitialized ::: WebApplicationApplicationContext : "
                              + WebApplicationContextUtils
                                      .getWebApplicationContext(initializingEvent
                                              .getServletContext()));
          }
  
          if (LogManager.isDebugOn()) {
              LogManager
                      .debug("AppServletContextListener ::: contextInitialized ::: RequiredWebApplicationApplicationContext : "
                              + WebApplicationContextUtils
                                      .getRequiredWebApplicationContext(initializingEvent
                                              .getServletContext()));
          }
  
          YTConnectorMgr ytConnectorMgr = (YTConnectorMgr) WebApplicationContextUtils
                  .getWebApplicationContext(initializingEvent.getServletContext())
                  .getAutowireCapableBeanFactory()
                  .autowire(YTConnectorMgr.class,
                          AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
  
          if (LogManager.isDebugOn()) {
              LogManager
                      .debug("AppServletContextListener ::: contextInitialized ::: ytConnectorMgr : "
                              + ytConnectorMgr);
          }
      }
  }
  </code></pre>
  
  <p><strong>The web.xml</strong></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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      id="WebApp_ID" version="3.0"&gt;
  
  
      &lt;!-- &lt;listener&gt;
          &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
      &lt;/listener&gt;
  
      &lt;context-param&gt;
      &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
      &lt;param-value&gt;/WEB-INF/sapphire-security.xml&lt;/param-value&gt;
      &lt;/context-param&gt; --&gt;
  
      &lt;listener&gt;
          &lt;listener-class&gt;sapphire.social.connector.listener.AppServletContextListener&lt;/listener-class&gt;
      &lt;/listener&gt;
  
      &lt;servlet&gt;
      &lt;servlet-name&gt;central-config&lt;/servlet-name&gt;
          &lt;servlet-class&gt;
                    org.springframework.web.servlet.DispatcherServlet
          &lt;/servlet-class&gt;
          &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
    &lt;/servlet&gt;
  
    &lt;servlet-mapping&gt;
      &lt;servlet-name&gt;central-config&lt;/servlet-name&gt;
          &lt;url-pattern&gt;/&lt;/url-pattern&gt;
    &lt;/servlet-mapping&gt;
  
  &lt;/web-app&gt;
  </code></pre>
  
  <p><strong>central-config-servlet.xml</strong></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:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
          http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"&gt;
  
      &lt;context:component-scan base-package="sapphire" /&gt;
  
      &lt;mvc:annotation-driven /&gt;
  
  
      &lt;!-- Start : To by-pass MVC view resolution and pass the response to appropriate 
          media type view resolvers/views Deprecated approach since Spring 3.2.x --&gt;
      &lt;bean
          class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"&gt;
          &lt;property name="favorPathExtension" value="false"&gt;&lt;/property&gt;
          &lt;property name="mediaTypes"&gt;
              &lt;map&gt;
                  &lt;entry key="json" value="application/json" /&gt;
                  &lt;entry key="xml" value="text/xml" /&gt;
                  &lt;entry key="htm" value="text/html" /&gt;
              &lt;/map&gt;
          &lt;/property&gt;
          &lt;property name="viewResolvers"&gt;
              &lt;list&gt;
                  &lt;bean class="org.springframework.web.servlet.view.BeanNameViewResolver" /&gt;
                  &lt;bean
                      class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt;
                      &lt;property name="prefix" value="/WEB-INF/views/" /&gt;
                      &lt;property name="suffix" value=".jsp" /&gt;
                  &lt;/bean&gt;
              &lt;/list&gt;
          &lt;/property&gt;
          &lt;!-- &lt;property name="defaultContentType" value="application/json" /&gt; &lt;property 
              name="defaultViews"&gt; &lt;list&gt; &lt;bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" 
              /&gt; &lt;/list&gt; &lt;/property&gt; --&gt;
      &lt;/bean&gt;
      &lt;!-- End : To by-pass MVC view resolution and pass the response to appropriate 
          media type view resolvers/views Deprecated approach since Spring 3.2.x --&gt;
  
  
      &lt;task:scheduler id="scheduler" pool-size="5" /&gt;
  
      &lt;task:annotation-driven scheduler="scheduler" /&gt;
  
  &lt;/beans&gt;
  </code></pre>
  
  <p>I attempted to retrieve both WebApplicationContext and Required WebApplicationContext - the former came null and the latter requires a ContextLoaderListener</p>
  
  <pre><code>Fri Nov 15 12:05:55 IST 2013 [Thread-2] AppServletContextListener ::: contextInitialized :::
  Nov 15, 2013 12:05:55 PM org.apache.catalina.core.StandardContext listenerStart
  SEVERE: Exception sending context initialized event to listener instance of class sapphire.social.connector.listener.AppServletContextListener
  java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered?
      at org.springframework.web.context.support.WebApplicationContextUtils.getRequiredWebApplicationContext(WebApplicationContextUtils.java:84)
      at sapphire.social.connector.listener.AppServletContextListener.contextInitialized(AppServletContextListener.java:44)
      at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4723)
      at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5226)
      at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5221)
      at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
      at java.util.concurrent.FutureTask.run(Unknown Source)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
      at java.lang.Thread.run(Unknown Source)
  
  Nov 15, 2013 12:05:55 PM org.apache.catalina.core.StandardContext startInternal
  SEVERE: Error listenerStart
  Nov 15, 2013 12:05:55 PM org.apache.catalina.core.StandardContext startInternal
  SEVERE: Context [/Sapphire] startup failed due to previous errors
  Fri Nov 15 12:05:55 IST 2013 [Thread-2] AppServletContextListener ::: contextInitialized ::: WebApplicationApplicationContext : null
  Fri Nov 15 12:05:55 IST 2013 [stop children - Catalina:j2eeType=WebModule,name=//tenantarchtst.lntinfotech.com/Sapphire,J2EEApplication=none,J2EEServer=none] AppServletContextListener ::: contextDestroyed :::
  Nov 15, 2013 12:05:55 PM org.apache.coyote.AbstractProtocol start
  INFO: Starting ProtocolHandler ["http-bio-8081"]
  Nov 15, 2013 12:05:55 PM org.apache.coyote.AbstractProtocol start
  INFO: Starting ProtocolHandler ["ajp-bio-8010"]
  Nov 15, 2013 12:05:55 PM org.apache.catalina.startup.Catalina start
  INFO: Server startup in 15184 ms
  </code></pre>
  
  <p>Just for reference, giving the bean that I want to inject in the ServletContextListener :</p>
  
  <pre><code>@Component(value = "YTConnectorMgr")
  public class YTConnectorMgr extends ConnectorMgr {
  
      private static int maxWorkerThreads = 5;
  
      public YTConnectorMgr(int maxWorkerThreads, ConnectorType connectorType) {
          super(maxWorkerThreads, connectorType);
      }
  
  }
  </code></pre>
  
  <p><strong>I'm having a single config xml file which is taken care by the DispatcherServlet - ideally, I don't require a ContextLoaderListener! But even <a href="https://stackoverflow.com/questions/5511152/dependency-inject-servlet-listener">this previous post</a> dictates the use of a ContextLoaderListener. As pointed by M.Deinum, I should NOT be duplicating my beans !!!</strong></p>