title: Spring injection Into Servlet
body: <p>So I have seen this question:</p>
  
  <p><a href="https://stackoverflow.com/questions/9127807/spring-dependency-injection-to-other-instance">Spring dependency injection to other instance</a></p>
  
  <p>and was wondering if my method will work out.</p>
  
  <p>1) Declare beans in my Spring application context</p>
  
  <pre><code>    &lt;bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource"&gt;
          &lt;property name="driverClassName" value="${jdbc.driverClassName}"/&gt;
          &lt;property name="url" value="${jdbc.url}" /&gt;
          &lt;property name="username" value="${jdbc.username}" /&gt;
          &lt;property name="password" value="${jdbc.password}" /&gt;
          &lt;property name="initialSize" value="${jdbc.initialSize}" /&gt;
          &lt;property name="validationQuery" value="${jdbc.validationQuery}" /&gt; 
          &lt;property name="testOnBorrow" value="${jdbc.testOnBorrow}" /&gt;
      &lt;/bean&gt;
  
      &lt;bean id="apiData" class="com.mydomain.api.data.ApiData"&gt;
          &lt;property name="dataSource" ref="dataSource" /&gt;
          &lt;property name="apiLogger" ref="apiLogger" /&gt;
      &lt;/bean&gt;
  
      &lt;bean id="apiLogging" class="com.mydomain.api.data.ApiLogger"&gt;
          &lt;property name="dataSource" ref="dataSource" /&gt;
      &lt;/bean&gt;
  </code></pre>
  
  <p>2) Override my servlet's init method as shown:</p>
  
  <pre><code>    @Override
      public void init(ServletConfig config) throws ServletException {
         super.init(config);
  
         ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
  
         this.apiData = (ApiData)ac.getBean("apiData");
         this.apiLogger = (ApiLogger)ac.getBean("apiLogger");
      }
  </code></pre>
  
  <p>Will this work or is Spring not yet ready to deliver beans to my servlet at this point in the web applications deployment? Do I have to do something more traditional like putting the beans in <code>web.xml</code>?</p>