繁体   English   中英

spring父上下文和子上下文之间有什么区别?

[英]What is the difference between spring parent context and child context?

我正在阅读spring doc核心容器我希望在注入协作者时了解ref parent的目的然后我发现了父上下文子上下文或父容器和当前容器的概念这是我对它感到困惑的部分这部分博士

通过parent属性指定目标bean会创建对当前容器的父容器中的bean的引用。 parent属性的值可以与目标bean的id属性相同,也可以与目标bean的name属性中的一个值相同,并且目标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父母的目的是什么,请提前谢谢

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

Application Context是Spring的高级容器。 与BeanFactory类似,它可以加载bean定义,将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启动应用程序中的应用程序上下文层次结构示例。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM