spring-framework-reference(5.1.1.RELEASE)中文版——Core部分 (10)

一种特例,可以从自定义作用域接收销毁回调——例如,对于单例bean中包含的请求作用域的内部bean。内部bean实例的创建与其包含的bean绑定在一起,但是销毁回调允许它参与请求范围的生命周期。这不是一个常见的场景。内部bean通常只是共享其包含bean的作用域。

Collections <bean> <!-- results in a setAdminEmails(java.util.Properties) call --> <property> <props> <prop key="administrator">administrator@example.org</prop> <prop key="support">support@example.org</prop> <prop key="development">development@example.org</prop> </props> </property> <!-- results in a setSomeList(java.util.List) call --> <property> <list> <value>a list element followed by a reference</value> <ref bean="myDataSource" /> </list> </property> <!-- results in a setSomeMap(java.util.Map) call --> <property> <map> <entry key="an entry" value="just some string"/> <entry key ="a ref" value-ref="myDataSource"/> </map> </property> <!-- results in a setSomeSet(java.util.Set) call --> <property> <set> <value>just some string</value> <ref bean="myDataSource" /> </set> </property> </bean>

映射键或值或集值的值也可以是以下任何元素:

bean | ref | idref | list | set | map | props | value | null Collection Merging

Spring容器还支持合并集合。应用程序开发人员可以定义父元素

Spring容器还支持合并集合。应用程序开发人员可以定义父元素

下面的例子演示了集合合并:

<beans> <bean abstract="true"> <property> <props> <prop key="administrator">administrator@example.com</prop> <prop key="support">support@example.com</prop> </props> </property> </bean> <bean parent="parent"> <property> <!-- the merge is specified on the child collection definition --> <props merge="true"> <prop key="sales">sales@example.com</prop> <prop key="support">support@example.co.uk</prop> </props> </property> </bean> <beans>

注意,在子bean定义的adminemail属性的元素上使用merge=true属性。当容器解析并实例化子bean时,生成的实例具有adminEmail属性集合,其中包含将子bean的adminemail集合与父组件的adminemail集合合并的结果。下面的清单显示了结果:

administrator=administrator@example.com sales=sales@example.com support=support@example.co.uk

子属性集合的值集继承了来自父元素

Limitations of Collection Merging

不能合并不同的集合类型(例如映射和列表)。如果您确实试图这样做,则会抛出一个适当的异常。merge属性必须在较低的继承子定义上指定。在父集合定义上指定merge属性是多余的,不会导致所需的合并。

Strongly-typed collection

随着Java 5中泛型类型的引入,您可以使用强类型集合。也就是说,可以声明一个集合类型,使其只能包含(例如)字符串元素。如果使用Spring依赖于将强类型集合注入bean,则可以利用Spring的类型转换支持,以便在添加到集合之前将强类型集合实例的元素转换为适当的类型。下面的Java类和bean定义说明了如何做到这一点:

public class SomeClass { private Map<String, Float> accounts; public void setAccounts(Map<String, Float> accounts) { this.accounts = accounts; } } <beans> <bean> <property> <map> <entry key="one" value="9.99"/> <entry key="two" value="2.75"/> <entry key="six" value="3.99"/> </map> </property> </bean> </beans>

当为注入准备好某某bean的accounts属性时,强类型映射的元素类型的泛型信息可以通过反射得到。因此,Spring的类型转换基础结构将各种值元素识别为浮点类型,并将字符串值(9.99、2.75和3.99)转换为实际的浮点类型。

Null and Empty String Values

Spring将属性等的空参数视为空字符串。以下基于xml的配置元数据片段将email属性设置为空字符串值("")。

<bean> <property value=""/> </bean>

上述示例相当于以下Java代码:

exampleBean.setEmail("");

元素

<bean> <property> <null/> </property> </bean>

上述示例相当于以下Java代码:

exampleBean.setEmail(null); 使用p-namespace的XML快捷方式

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzdjpw.html