【Spring学习10】依赖配置:bean的父子继承

前端之家收集整理的这篇文章主要介绍了【Spring学习10】依赖配置:bean的父子继承前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Spring Bean的父子继承主要是为了统一定义Spring Bean的公共属性、作业范围scope,并避免了冗余和修改的繁琐。

  1. <beans>
  2. <bean id="notify" class="twm.spring.start.NotifyServiceByCellPhoneImpl" />
  3. <bean id="parent" abstract="true" class="example.ComplexObject">
  4. <property name="notifyservice" ref="notify"/>
  5. <property name="adminEmails">
  6. <props>
  7. <prop key="administrator">administrator@example.com</prop>
  8. <prop key="support">support@example.com</prop>
  9. </props>
  10. </property>
  11. </bean>
  12.  
  13. <bean id="child" parent="parent">
  14. <property name="adminEmails">
  15. <props merge="true">
  16. <prop key="sales">sales@example.com</prop>
  17. <prop key="support">support@example.co.uk</prop>
  18. </props>
  19. </property>
  20. </bean>
  21. <beans>

可以看到child bean无需声明class,它用parent声明了父对象,这样就继承了父对象的class声明,以及notifyservice属性值,adminEmails的值也会从父对象继承并合并。

如果父对象声明属性abstract="true",则不能实例化,因为它是抽象的bean。容器内部的preInstantiateSingletons()方法会忽略抽象bean。在作为子bean的纯模板时,非常有用。

猜你在找的设计模式相关文章