As I understand, a Spring based web application is initialized as below:
Step 1: Servlet container (e.g. Tomcat)
locates the implementation
But why do we have to create these 2 contexts in different places, i.e. DispatcherServlet and ContextLoaderListener
Because the two contexts are supposed to be different but yet have a hierarchical relation in order to be able to override. Typically the context loaded using ContextLoaderListener
is "root" context which belongs to the whole application while the one initialized using DispatcherServlet
is actually specific to that servlet. Technically you can have multiple servlets in an application and so multiple such contexts each specific for respective servlet but having same root context. For more details see another of my answer here.