What is the difference between spring parent context and child context?

后端 未结 1 1005
刺人心
刺人心 2021-02-15 06:51

I was reading spring doc the core container I want to understand the purpose of ref parent when inject collaborators then I found this notion of parent context

1条回答
  •  情歌与酒
    2021-02-15 07:45

    The beans of the Spring run inside an application context.

    The Application Context is Spring's advanced container. Similar to BeanFactory, it can load bean definitions, wire beans together, and dispense beans upon request. Additionally, it adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners. This container is defined by org.springframework.context.ApplicationContext interface. https://www.tutorialspoint.com/spring/spring_applicationcontext_container.htm

    For each application context you can have many configuration files, configuration classes or a mix of both.

    You can create an application context with a code like this:

    ApplicationContext context = new FileSystemXmlApplicationContext("Beans.xml");
    

    And obtain the beans with context.getBean or with @autowired.

    There are some cases when you want(or need) to have a context hierarchy. In these cases Spring provides a way of specifying a parent context. If you look at this constructor, you will see that it receives a context parent.

    http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/support/FileSystemXmlApplicationContext.html#FileSystemXmlApplicationContext-org.springframework.context.ApplicationContext-

    As you can see the parent context is the same type of a child context, they both are http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/ApplicationContext.html.

    The difference is that they are related through a parent/child relationship. Not a compose(import) relationship.

    The most common case where you see this is in a Spring MVC application, this applications have 2 context, the first is the dispatcher servlet context and the other one is the root context. Here you can see the relationship http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-servlet

    And here you can see an example of application context hierarchy in spring boot applications.

    https://dzone.com/articles/spring-boot-and-application-context-hierarchy

    0 讨论(0)
提交回复
热议问题