Click here to Skip to main content
13,295,178 members (75,060 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


2 bookmarked
Posted 8 Sep 2011

How to inject Spring beans into Servlets

, 2 Oct 2011
Rate this:
Please Sign up or sign in to vote.
This can be achieved in 3 simple steps:

1. Implement HttpRequestHandler

First of all, your servlet class must implement the org.springframework.web.HttpRequestHandler interface and provide an implementation for the handleRequest() method just like you would override doPost().

2. Declare the servlet as a Spring Bean

You can do this by either adding the @Component("myServlet") annotation to the class, or declaring a bean with a name myServlet in applicationContext.xml.
public class MyServlet implements HttpRequestHandler {

3. Declare in web.xml a servlet named exactly as the Spring Bean

The last step is to declare a new servlet in web.xml that will have the same name as the previously declared Spring bean, in our case myServlet. The servlet class must be

Now you are ready to inject any spring bean in your servlet class.
public class MyServlet implements HttpRequestHandler {
        private MyService myService;


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Technical Lead Endava Ltd.
Romania Romania
My name is Madalin Ilie. Currently I'm a Development Lead at Endava Romania (

You may also be interested in...

Comments and Discussions

GeneralReason for my vote of 5 ITS SPECIFIC Pin
mohitjilit3-Oct-11 19:49
membermohitjilit3-Oct-11 19:49 
GeneralReason for my vote of 5 maybe add component-scan ? Pin
unludo16-Sep-11 3:41
memberunludo16-Sep-11 3:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171207.1 | Last Updated 2 Oct 2011
Article Copyright 2011 by ludovicianul
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid