May 4, 2010

Understanding the Different ApplicationContexts in Spring Application

As a beginner to spring, one might often not know the difference between the several applicationContexts that we use in a spring application. Spring documentation is the best place that can really guide you though the process of completely getting this clarified!

But here is the abridged version for a quick understanding of the differences between the various configuration files that we use in a spring application.

  • Understand that the webapplicationcontext denotes the xml configuration file that is invoked by the DispatcherServlet within the spring enabled web application. This is the xxx-sevlet.xml file where you define the details of the handler mappings, view configuration, controller bean definitions and other web related beans. This also includes the definition of the locale and theme resolvers that you might use within your application. You can have a single or multiple web application contexts within your spring enabled web application.
  • The other application contexts that are used within the spring enabled web application are usually loaded by the contextLoaderListener/servlet as shown in the figure below. This can be a single file (applicationContext.xml) or multiple applicationcontexts with names based on the modularization that you make within the application. these application contexts are very different from the web application contexts. They contain the details of the datasources, daos, services, other component beans and the details of the transaction managers used within your application.
  • Note that the webapplicationcontext used within any application would have access to all beans defined within the application contexts that are loaded by the ContextLoaderListener.
                        
  • When you configure the transaction manager, it is important to understand the fact that the Txmanager will search for @Transactional type annotations in all the beans defined within the same application context only! So, this means that you cannot define the TxManager in the applicationContext and have your services and dao beans defined in the webapplicationcontext of your application for this would result in org.hibernate.HibernateException: No Hibernate Session bound to thread. Before you go ahead, ensure that the above differences are very clear and configure your application accordingly!
Technorati Tags: , , , ,

1 comment: