Understanding contexts in Spring MVC

The whole idea behind this design is to handle different architectural layers in a typical web application and provide for inheritance / override mechanism for beans across contexts. Each type of context in Spring is related to different architectural layer for e.g, web layer, service layer etc.

A Spring based web application can have multiple dispatcher servlet configured (although in majority of cases its a single servlet – but dispatcher serlvet is a servlet nonetheless and there could be multiple configured in web.xml). These can be configured to handle different url patterns. So obviously each is a different servlet and hence can have different Spring web Application context. Each of these can contain different configurations for Spring web layer like controllers,interceptors,view resolvers,locale resolvers etc. as these typically belong to the web layer of an application. All these configurations and beans are private to each dispatcher servlet so they are not visible to each other. Hence having a seperate spring web application context makes sense to enable this privacy. However there are other beans which are designed to be shared hence belong to a root context. So all the shareable things belong to the root context and it can be considered global for this web application.

Each dispatcher servlet inherits all the beans defined in the root context. However the important point to note is that the shared beans can be overridden by respective dispatcher servlet specific beans. So in web applications root context can be viewed as something which is inherited but can be overridden.

Leave a Comment