views:

40

answers:

1

The scenario:

  1. Start the app and load ClassPathXmlApplicationContext in main(), this starts a Jetty webapp.
  2. dispatcher servlet then loads a XmlWebApplicationContext
  3. dispatcher servlet then looks for WEB-INF/applicaitonContext.xml to load as the root context

I'm just trying to get my head around contexts.

  • Should I use 3 contexts as listed above?
  • Should I be using the 1st context as the root context and not allowing dispatcher to load the default WEB-INF/applicationContext?
  • Should I be creating a parent/child relationship between the 1st and 3rd contexts? (this is done for me between #2 and #3 contexts by the dispatcher servlet)

I'm just not really clear yet about how these contexts relate to one another, I just need a quick rundown on it.

+5  A: 

Context #1 is not connected to other contexts at all, it is just an implementation detail of how you start up your webserver (Jetty). Contexts #2 and #3 are somewhat explained in Spring reference documentation.

  • Context #2 is loaded from WEB-INF/[servlet-name]-servlet.xml. As there can be many DispatcherServlets, there may be more than one such a context in single webapp, for different servlets.
  • Context #3 is typically loaded from WEB-INF/applicationContext.xml and you have to take special steps to have it loaded (use ContextLoaderListener). This loaded context becomes the parent context (shared) of all specific servlet contexts in particular web application. As such, it is suitable for loading business service beans and database access beans.

The setup you outlined is perfectly OK. In fact, I would call it the recommended setup, as it keeps things simple and close to the way Spring contexts are constructed in a typical webapp.

However:

You may get rid of context #3 if you do not want to keep your business beans in separate context. However, I would recommend you to keep them separate (you might need to move them to a different machine later on and make available over some sort of remoting mechanism).

Another reason to get rid of context #3: you might want to share your business beans among several webapps. The in order to achieve this you would need a special subclass of Spring ContextLoader and then do some magic while Jetty is starting up your webapps. I have done this and can provide some advice, if needed.

Finally, you may get rid of context #1 and replace that with old-school pure java code that would bootstrap Jetty. This decision is 100% up to you and matter of preference. For the record, I also like to use a separate Spring applicationContext for bootstrapping Jetty.

Neeme Praks