1

Per the Spring Documentation, application context is:

Central interface to provide configuration for an application. This is read-only while the application is running, but maybe reloaded if the implementation supports this.

In some applications, there are multiple application contexts. What's the purpose and benefit of having multiple application contexts? I want to understand the logic behind it. Why would one do it?

P.S: In spring doc use is written. I want to know the pros of having multiple application contexts and the rationale behind it.

kulsin
  • 398
  • 4
  • 18
  • 1 root context, containing the general beans (like datasource, connection factories, services etc.) and another containing only web related things (controllers, viewresolves etc) and maybe another for the SOAP webservices. That way you can share the common parts (datasources, services etc.). – M. Deinum Mar 12 '20 at 07:41
  • Note that while it's certainly _possible_ to do this, I've never in my career actually worked with such an application. – chrylis -cautiouslyoptimistic- Mar 12 '20 at 07:45
  • 1
    You didn't have an application with a `ContextLoaderListener` and `DispatcherServlet`? Each has there own context (where the `ContextLoaderListener` has the root one, and the `DispatcherServlet` one a child one which should only contain web related parts). – M. Deinum Mar 12 '20 at 07:49

3 Answers3

4

The root context is the parent of every dispatcher servlet context/child context. Beans defined in root context are visible to each dispatcher servlet context/child context but not vice-versa.

Typically, root context is used to define all cross-cutting beans such as security, transactions, and other configurational beans, while the dispatcher context or child context contains those beans that are specifically related to MVC.

We create multiple dispatcher servlets when we need multiple sets of MVC configuration. For e.g. we may have a REST API alongside a traditional MVC application or an unsecured and a secure section of a website.

enter image description here

kulsin
  • 398
  • 4
  • 18
0

Cannot comment so putting the answer:-

Java Spring multiple ApplicationContext

Hope this answer your question

backdoor
  • 891
  • 1
  • 6
  • 18
0

It is useful to implement a layered architecture (model objects, data access, services, web services, mvc app etc).

As M.Deinum said it is good to have one root context that loads the others and helps keeping them separated.

Here is the official doc for the architecture of Spring Framework applications: https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/overview.html