Friday, March 12, 2010

Integrating a Spring application context with a web application

I think I finally figured it out last night. Most of the tutorials and documentation on using Spring's DI container seemed to only show to programmatically create an ApplicationContext by instantiating a subclass of it in a main method. So I was trying to figure out where you were supposed to do this in a web application. I had forgotten that you could use a ContextLoaderListener that would create an ApplicationContext (known as the root app context) from the xml files listed in an init-param in the web app context. But even when I rediscovered that, I had trouble figuring out if my Jersey Controllers were supposed to manually get beans from this root app context somehow.

So I spent a while browsing through various tutorials and the Spring documentation, and asked a lot of questions in the #spring IRC channel. At one point it eventually clicked and I figured out that most web frameworks need to provide some way of integrating with Spring, as opposed to this being completely standardized from Spring's side. The thing that made me figure this out was that I looked at how Spring MVC integrates with Spring beans and how Jersey integrates with Spring beans.

- Spring MVC has a DispatcherServlet that retrieves beans which extend Controller from an application context on the classpath that is named servletname-servlet.xml
- Jersey retrieves classes annotated with @Component from the root web app context
- Struts uses a Spring plugin that defines the application context file where the required Struts Actions are wired

And when I realized this, I noticed why I had been going about it the wrong way earlier when I was trying to figure out how to get the root web app context to manually get my beans from there. Although I also learned about Spring's WebApplicationContextUtils which would allow me to do that if needed.

No comments:

Post a Comment