How to Inject Spring Beans into Servlets Revisited.

Back in November I wrote a post about How to Inject Spring Beans into Servlets, since then one of the comments made on the post by angel, mentioned an interface and Servlet that comes with spring that does this the proper spring way. Thank you very much angel, this is what I was looking for before I wrote the last post 🙂

The proper way how this should be achieved is to write a class that implements HttpRequestHandler and define this class in your applicationContext.xml. Then you define a servlet in web.xml with a class of HttpRequestHandlerServlet and make sure the name of the servlet is the same as the bean you defined in applicationContext.xml.

First lets write a class that we want to inject into a servlet…

package name.kayley.httprequesthandlertest;

public interface ServiceToInject {
  public String someMethod();
}
package name.kayley.httprequesthandlertest;

public class ServiceToInjectImpl implements ServiceToInject {
  public String someMethod() {
      return "someMethod called";
  }
}

Next we’ll write a class that implements the HttpRequestHandler this is basically our servlet.

package name.kayley.httprequesthandlertest;

public class MyHttpRequestHandler implements HttpRequestHandler {

   private ServiceToInject serviceToInject;

   public void setServiceToInject(ServiceToInject serviceToInject) {
       this.serviceToInject = serviceToInject;
   }

   public void handleRequest(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException {

       System.out.println("******* HELLO *******");
       System.out.println(serviceToInject.someMethod());
   }
}

Next all we need to do is configure our web.xml and applicationContext.xml…

First applicationContext.xml…

<xml version="1.0" encoding="UTF-8">
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

    <bean id="serviceToInject" class="name.kayley.httprequesthandlertest.ServiceToInjectImpl"/>

    <bean id="myhttprequesthandler" class="name.kayley.httprequesthandlertest.MyHttpRequestHandler">
        <property name="serviceToInject" ref="serviceToInject"/>
    </bean>

</beans>

And finally configure your web.xml …

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

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>myhttprequesthandler</servlet-name>
        <servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>myhttprequesthandler</servlet-name>
        <url-pattern>/MyServlet</url-pattern>
    </servlet-mapping>
</web-app>

Now run your web app and go to http://localhost:8080/MyServlet

You should see in your console log the output of your injected servlet…

******* HELLO *******
someMethod called

Brilliant 🙂 Thanks again angel.

Technorati Tags: , , , ,

21 Replies to “How to Inject Spring Beans into Servlets Revisited.”

  1. There may be a better way to do this, but I was able to use this workaround to accomplish the load-on-startup behavior.. 1) Implement as above – you don't need to actually put anything in the handlerequest, but you should have a public initialization method of some sort (i.e. – init)2) Add the <load-on-startup>1</load-on-startup> stuff to the servlet declaration in web.xml3) Declare the handler as a non-lazy-loaded bean in applicationContext.xml: <bean id="MyInitHandler" class="com.example.MyInitHandler" lazy-init="false" init-method="init" scope="singleton" />4) Profit!5) Seriously, though, that was all that was needed. The init() method was run on startup. Enjoy!

  2. Hi,I try to make my own webapp but I have a problem when I launch my tomcat. I have an error with the load of the context. The tomcat logs message is:17 sept. 2009 08:47:06 org.apache.catalina.core.StandardContext startGRAVE: Error listenerStart17 sept. 2009 08:47:06 org.apache.catalina.core.StandardContext startDo you have any idea about my problem?Thanks

  3. Hey Andy,what should be the value of scope attribute when creating spring beans from servlet container.My question is servlet creates different threads for each incoming user request and spring container by default supplies same instance of the bean for all requests,is in't that each incoming user request will get same spring bean or each request get different beanThanks in Advance

  4. Hi Andy,Please could u put the program for:Calling a spring bean from servlet with the jsp…Please do help me..i'm new to springThanks in advance

  5. The bean to be injected and the .class file it refers to are in a JAR which is in the WAR. Using the code provided, the bean is not found.

  6. Wonderful! This really saved my day. I was starting to fall into a deep black hole when I realized that I could not dependency inject into a servlet.Thanks for this blog!

  7. Thank you.This helped me quickly clean up some awful code in which I was setting servlet collaborators in the init method. Now I got some POJO love going and my unit tests are much simpler.

  8. Great post! Very useful! But do you have any idea how to access the init-params from the servlet config in your servlet class?Thanks,Eric

  9. I'm sure this is documented somewhere in Spring's doco, still, nothing beats a live example and a 5-minute fix for a "not-so-expert" like myself.Thanks a lot.

  10. One thing that I discovered regarding this is – the Spring HttpRequestHandlerServlet requires your HttpRequestHandler implemented bean to be registered in the Spring root context. It won't work if you have your bean (HttpRequestHandler implementation) in the Spring dispatcher context. You might need to implement your own HttpRequestHandlerServlet that supports both the contexts.

  11. Thanks Pal , I too was looking for it , done the work around and putted a "TODO" tag ..But now I can remove that tag . thanks again 🙂

  12. Dear friends,I have been getting crazy with this topic. I could not undertand why I was receiving a NullPointException.The problem was in:public class xServlet implements HttpRequestHandler{When I used the servlet class in that way (without extending of HttpServlet) the application can not find the servlet class.But if I extended from HttpServlet, then the NullPointerException mentioned appeared.Finally I have realized that I had to extend from HttpRequestHandlerServlet instead of HttpServlet. It solves the problem!public class LogoServlet extends HttpRequestHandlerServlet implements HttpRequestHandler.

Comments are closed.