【问题标题】:What is the difference between spring parent context and child context?spring 父上下文和子上下文有什么区别?
【发布时间】:2019-01-07 14:19:51
【问题描述】:

我正在阅读 spring 文档核心容器我想了解注入协作者时 ref parent 的目的然后我发现了父上下文子上下文或父容器和当前容器的概念这是部分我对此感到困惑: This part of doc

通过 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>

有人可以给我一些帮助或这两种上下文的例子吗?以及 ref 父级的目的是什么 提前谢谢你

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:

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

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

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

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

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

    并使用context.getBean@autowired 获取bean。

    在某些情况下,您希望(或需要)拥有上下文层次结构。在这些情况下,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/ApplicationContext.html

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

    最常见的情况是在 Spring MVC 应用程序中,该应用程序有 2 个上下文,第一个是调度程序 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

    【讨论】:

    • 如你所说,很好地解释了 spring mvc 是一个最好的例子,谢谢
    • 我认为 DispatcherServlet 是在 servlet/web 容器中启动 Spring 框架的第一个入口点。 Tomcat 等,所以我想知道“根”应用程序上下文是在哪里定义的以及它是如何启动的......
    猜你喜欢
    • 2023-04-01
    • 2020-10-29
    • 2017-10-07
    • 2012-05-05
    • 2010-09-27
    • 2012-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    相关资源
    最近更新 更多