@Deprecated: How to Inject Spring Beans into Servlets.

This post has been Deprecated, see this post instead


A couple of months ago I was working on an application that used Servlets as entry points to an application, sort of like a web service. This was a new application and I decided to use the Spring framework for dependancy injection and to make using Hibernate easier.

I am fairly new to Spring and never needed to inject any spring beans into servlet before, and I thought there must be a way to do it. However after browsing through a number of websites, blog posts and forum posts, it appeared that there wasn't a clean spring way to do this.

Solution 1

In the end I read somewhere that you could inject spring beans into the ServletContext, so I took this route.

With this you have to declare this little piece in your applicationContext.xml



As you can see this puts the spring bean myBeanFromSpring into the servlet context. Therefore in your servlet code you can do the following...



Although this works it still doesn't feel very spring like.

Solution 2

There is another way to achieve the same thing. You can use WebApplicationContext and get the beans directly from Spring without having to inject anything into the servlet context.



Although this achieves the same thing and is probably more concise than Solution 1, it still is not achieving what I initially wanted, which was dependancy injection into the servlet.

Solution 3

Although I stayed with Solution 1 for the application it got me thinking. So I set out to write a sub class of HttpServlet that would use the servletContext solution and use reflection to figure out if the servlet had any setters on that spring should call.

My original servlet that had to do all the stuff with getting the servlet context suddenly looks a lot more spring-like...



And here is the source of the SpringDependencyInjectionServlet, go easy on it, Its the first version and it passes the unit tests i have written for it, use it at your own risk or as a starting point, but like I said it appears to work ok so far.

I have attempted to keep in with the spring autowiring of giving 2 options, autowire by type and by name, so you can override autowireByType if you want to autowire by name. I think they need some work as I believe that autowire by name should go off the name of the parameter to the setter method and not the setter method name itself... keep coming back for updates.



Technorati Tags: , , , ,