Why use Spring ApplicationContext hierarchies?
Asked Answered
G

1

56

I am trying to understand ApplicationContext hierarchies in spring.

I learned the following

  1. An ApplicationContext cannot have more than 1 parent ApplicationContext.
  2. When a given ApplicationContext cannot resolve a bean, it will pass on the resolution request to its parent.
  3. The parent of an ApplicationContext is specified in its constructor.

I would like to understand when to use ApplicationContext hierarchies (instead of a single ApplicationContext).

The best I could get from google was this. And what I understand is that if an application has a large number of beans defined at the various layers then each layer having its own ApplicationContext would be a benefit. What is not understood is what is the benefit of doing so and how is the benefit achieved?

Garlinda answered 27/2, 2011 at 10:16 Comment(2)
Hi! Seems the link you provided in question not pointed to the article about spring contexts :)Colo
Thanks for pointing it out @aggredi. I have struck the reference to the link.Garlinda
D
53

The classic use-case for this is when you have multiple Spring DispatcherServlet within a single webapp, with each of these servlets having their own app context, but which need to share beans between them. In this case, you add a 3rd context at the level of the webapp, which is the parent of each of the servlet appcontexts.

You can take this pattern further, for example if you have multiple webapps bundled into a single JavaEE EAR. Here, the EAR can have its own context, which is the parent of the individual webapp contexts, which is the parent of the servlet contexts, and so on. You have this hierarchy of responsibility.

In other situations, the context structure is dictated by some other factor. For example, Spring Security is independent of Spring MVC, and requires its configuration beans to go in the webapp context. If you want to use Spring MVC with it, then the config for that has to go into the servlet context, which has the root webapp context as its parent.

Deena answered 27/2, 2011 at 10:24 Comment(1)
In reading further, understood the following (skaffman has already indicated parts of this). Each Spring MVC webapp has one root application context and one servlet application context for each DispatcherServlet. The root application context is the parent of each servlet application context. Beans defined in "contextConfigLocation" (context-param in web.xml) are loaded into root application context. Beans in <servlet-name>-servlet.xml are loaded into servlet application context. If an EAR has multiple web apps, an EAR level application context can parent the root context of each webapp in EAR.Garlinda

© 2022 - 2024 — McMap. All rights reserved.