I am trying to understand ApplicationContext hierarchies in spring.
I learned the following
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?
Spring ApplicationContextIt represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the beans. The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata.
You can have two contexts within an application. If you have two contexts each will have its own singleton.
The ApplicationContext is the central interface within a Spring application that is used for providing configuration information to the application. It's created when the application starts running.
In order to have multiple context paths, you're limited to deploying the application multiple times with that convenient property set to what you want for each deployment. However, this is resource expensive because you're spinning up two applications for every one application you would normally spin up.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With