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 *******");

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=""

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

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


And finally configure your web.xml …

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns=""


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: , , , ,