Wednesday, October 20, 2010

Spring Root, Portlet, and Servlet Contexts

Note: the following pertains to spring-webmvc-portlet in Spring 2.5.6 with JSR-168 compliant portlets. It may be different in other versions.

web.xml defines how the root application context (an instance of XmlWebApplicationContext) should look for configuration to setup beans in its context. If you define one or more files in contextConfigLocation, it loads those to define the beans, etc. for the root application context, to be available for the entire webapp. If singleton scope (the default for beans), they will be instantiated and configured on webapp load.

For example, web.xml in the Jasig calendar portlet:

defines the following as config files to use for the root application context via contextConfigLocation:

portlet.xml defines how the portlet application context (an instance of XmlPortletApplicationContext) should look for configuration to setup beans in its context. If you define one or more files in contextConfigLocation, it loads those to define the beans, etc. for portlet application context, to be available for the entire webapp. If singleton scope (the default for beans), they will be instantiated and configured on portlet load, which does not happen until the first time the portlet is loaded (the first request to a page that contains that portlet).

For example, portlet.xml in the calendar portlet:

defines the following as config files to use for the portlet application context via contextConfigLocation:

web.xml also can define one or more additional servlets (e.g. for Ajax functionality). If the servlet-class is org.springframework.web.servlet.DispatcherServlet, it will look for (servlet-name)-servlet.xml as the spring config file that defines the beans for the servlet application context. I don't know for sure, but I'm guessing if singleton scope (the default for beans), they will be instantiated and configured on portlet load, which does not happen until the first time the portlet is loaded (the first request to a page that contains that portlet), unless the servlet is configured to load-on-startup in web.xml.

For example, web.xml in the calendar portlet:

defines a servlet with servlet-name "spring" as a org.springframework.web.servlet.DispatcherServlet with load-on-startup, so it will load (servlet-name)-servlet.xml which is spring-servlet.xml:

Defining the same context files both in web.xml and portlet.xml is usually wrong, because it basically means you are creating instances of beans in the root *and* portlet contexts. The portlet would always use the ones in the portlet contexts, so the root ones would be wasted, along with any resources they consumed.

Thanks to Eric Dalquist for pointing me in the right direction for this!

No comments: