Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Spring create an application context or container hierarchy?

According to The IoC Container, Spring can manage a context hierarchy or hierarchy of containers and then use the <ref parent="beanId"/> to refer to a bean in a parent context. What mechanism does Spring use to create this container hierarchy? Can one use the <import resource="application-context.xml"/> command to create this hierarchy? Please provide an example of an application context that forms a hierarchy.

like image 388
Derek Mahar Avatar asked Mar 14 '11 17:03

Derek Mahar


People also ask

How does Spring application context work?

The ApplicationContext InterfaceIt uses dependency injection to achieve inversion of control. The interfaces BeanFactory and ApplicationContext represent the Spring IoC container. Here, BeanFactory is the root interface for accessing the Spring container. It provides basic functionalities for managing beans.

What is application context container in Spring?

ApplicationContext is a corner stone of a Spring Boot application. It 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.

Does Spring provide application context?

Spring IoC container is responsible for instantiating, wiring, configuring, and managing the entire life cycle of objects. BeanFactory and ApplicationContext represent the Spring IoC Containers. ApplicationContext is the sub-interface of BeanFactory.

What makes Spring Framework a container?

The Spring container is at the core of the Spring Framework. The container will create the objects, wire them together, configure them, and manage their complete life cycle from creation till destruction. The Spring container uses DI to manage the components that make up an application.


1 Answers

Application context hierarchy is created automatically; for example every Spring MVC application creates separate context for each DispatcherServlet. This context is a child of a common parent context. This way each child context can access beans from parent context, but not the other way around. Also sibling contexts are separated and invisible for each other.

You can create context hierarchy manually to provide finer level of granularity in your project. This can be achieved e.g. using various constructors of ClassPathXmlApplicationContext.

<import> construct merges beans from imported file, so it is a way of physically dividing bean definitions into several files, but they all end up in one context. BTW it's a pity there is no XML tag to define child context file (?)

like image 93
Tomasz Nurkiewicz Avatar answered Oct 10 '22 09:10

Tomasz Nurkiewicz