2017-04-17 69 views
5

我正在阅读spring doc核心容器我想了解ref父母当注入合作者时的目的,然后我发现父上下文子上下文或父容器和当前容器的这个概念这是我混淆的部分它: This part of doc春天的父母上下文和子女上下文有什么区别?

通过父属性指定目标的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父的用途

回答

3

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

应用程序上下文是Spring的高级容器。类似于 BeanFactory,它可以将bean定义,wire beans加载到一起,并根据请求分配bean。此外,它还增加了更多的企业特定功能,例如从属性文件中解析 文本消息的能力以及将应用程序事件发布到感兴趣的事件侦听器的功能。这个容器是由org.springframework.context.ApplicationContext接口定义的 。 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/ApplicationContext.html

不同之处在于它们通过父母/子女关系相关。不是撰写(导入)关系。

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

在这里,你可以看到在春季启动应用程序的应用程序上下文结构的例子。

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

+0

好像你说的那样解释mvc是一个很好的例子,谢谢 –

相关问题