Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Java

How to inject Spring beans into Servlets

5.00/5 (2 votes)
2 Oct 2011CPOL 68.4K  
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.
Java
@Component("myServlet")
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 org.springframework.web.context.support.HttpRequestHandlerServlet.
HTML
<servlet>
    <display-name>MyServlet</display-name>
    <servlet-name>myServlet</servlet-name>
    <servlet-class>
        org.springframework.web.context.support.HttpRequestHandlerServlet
    </servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>myServlet</servlet-name>
    <url-pattern>/myurl</url-pattern>
</servlet-mapping>

Now you are ready to inject any spring bean in your servlet class.
Java
@Component("myServlet")
public class MyServlet implements HttpRequestHandler {
        
        @Autowired
        private MyService myService;

License

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