views:

52

answers:

2

Hi all,

This may be a relatively straight-forward question that I just haven't been searching for correctly, but I'm trying to use the Spring IoC container to configure my servlets. I have some additional handlers (that are private data members) and such that I would like to be configured at runtime. Is it possible to do this?

Right now I have my web.xml loading the servlets correctly, however, the problem is I'm not sure how to wire those instances to the Spring IoC container, or alternatively, wire the instances generated from the IoC container to the servlet container.

In my web.xml file, I'm setting up the ContextLoaderListener

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

And also configuring the correct location for the beans context

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
    /WEB-INF/beans.xml
  </param-value>
</context-param>

I also know that the beans.xml file is being parsed because I got several exceptions when I had typed things incorrectly.

Thoughts? Is there a better way to do this?

+2  A: 

I think most folks looking to do what you are just use the Spring MVC framework. In that case, the is a Spring class, and you just implement "Controllers" (instead of actual servlets).

That said, it's completely possible to do exactly what you're looking for. Check out FrameworkServlet (you can extend that) or DelegatingFilterPorxy (you could write a 'DelegatingSevletProxy' using this class as an example).

Drew Wills
Thanks, I'll look into that. I was thinking about using SpringMVC from the beginning and my own laziness prevented that. I'll go ahead and do it right this time ;-)
Chris Thompson
A: 

You should move your logic out of servlets, so that they are just thin wrappers that get a reference to a Spring app context, instantiate a bean from the context, pass it the HTTP request, session, anything else needed, and tell the bean to do the work.

Consider that you can't instantiate a servlet outside of a servlet container, so it can't be unit-tested. The IoC container can't instantiate it. It won't benefit from IoC or DI.

If you can, use Spring MVC; you'll probably want to move the logic in your servlets into controller classes.

Otherwise, take a look at org.springframework.web.context.ContextLoaderListener; from there you can see how Spring bootstraps itself.

Ladlestein
Drew's advice below looks good; his points about FrameworkServlet and DelegatingFilterProxy are probably better advice than reading the code I mentioned.
Ladlestein