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...
Next we'll write a class that implements the HttpRequestHandler this is basically our servlet.
Next all we need to do is configure our web.xml and applicationContext.xml...
First applicationContext.xml...
And finally configure your web.xml ...
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: java, spring, servlet, dependency injection, andy kayley