Spring父上下文和子上下文有什么区别?

2024-06-30

我正在阅读 spring doc 核心容器 我想了解其目的参考父级当注入协作者时,我发现了父上下文子上下文或父容器和当前容器的概念,这是我感到困惑的部分:文档的这一部分 https://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-ref-element

通过parent属性指定目标bean会创建一个 引用当前容器的父容器中的 bean 容器。父属性的值可以与以下任一属性相同 目标 bean 的 id 属性,或名称中的值之一 目标 bean 的属性,并且目标 bean 必须位于父级中 当前容器的容器。您使用此 bean 参考变体 主要是当你有容器的层次结构并且你想包装一个 父容器中的现有 bean 具有代理,该代理将具有 与父 bean 名称相同。

<!-- in the parent context -->
<bean id="accountService" class="com.foo.SimpleAccountService">
    <!-- insert dependencies as required as here -->
</bean>
<!-- in the child (descendant) context -->
<bean id="accountService" <!-- bean name is the same as the parent bean -->
    class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="target">
        <ref parent="accountService"/> <!-- notice how we refer to the parent bean -->
    </property>
    <!-- insert other configuration and dependencies as required here -->
</bean>

有人可以给我一些帮助或这两种类型的上下文的例子吗?其目的是什么参考父级先感谢您


Spring 的 bean 在应用程序上下文中运行。

Application Context 是 Spring 的高级容器。如同 BeanFactory,它可以加载bean定义,将bean连接在一起,以及 根据要求分配豆子。此外,它还添加了更多 企业特定的功能,例如解决问题的能力 来自属性文件的文本消息以及发布的能力 将事件应用程序发送给感兴趣的事件侦听器。这个容器是 由 org.springframework.context.ApplicationContext 接口定义。https://www.tutorialspoint.com/spring/spring_applicationcontext_container.htm https://www.tutorialspoint.com/spring/spring_applicationcontext_container.htm

对于每个应用程序上下文,您可以有许多配置文件、配置类或两者的混合。

您可以使用如下代码创建应用程序上下文:

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

并获得豆子context.getBean或与@autowired.

在某些情况下,您希望(或需要)拥有上下文层次结构。在这些情况下,Spring 提供了一种指定父上下文的方法。如果您查看此构造函数,您将看到它接收一个上下文父级。

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

正如您所看到的,父上下文与子上下文的类型相同,它们都是http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/ApplicationContext.html http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/ApplicationContext.html.

不同之处在于它们通过父/子关系相关。不是组合(导入)关系。

最常见的情况是在 Spring MVC 应用程序中,该应用程序有 2 个上下文,第一个是调度程序 servlet 上下文,另一个是根上下文。 在这里你可以看到关系http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-servlet http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-servlet

在这里您可以看到 Spring Boot 应用程序中应用程序上下文层次结构的示例。

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring父上下文和子上下文有什么区别? 的相关文章

随机推荐