Dependencies and configuration in detail

来源:互联网 发布:小语网络加速器官网 编辑:程序博客网 时间:2024/05/16 01:45

 

-Straight values(primitives, Strings and so on)

-References to other beans(collaborators)

-Inner beans

-Collections

-Null and empty string values

-XML shortcut with the p-namespace

-Compound property names

 

--------------------------------------------------------------

-Straight values(primitives, Strings and so on)

对于基本数据类型,可使用如下方式配置:

1)直接使用<property name="" value=""/>来进行配置,如:

 

 

2)使用p-namespace进行配置:

 

 

3)使用idref。

  The idref element is simply an error-proof way to pass the id (string value - not a reference) of another bean in the container to a <constructor-arg/>or <property/>element.

 

如下两种方式等价:

 

 

 

 

这两种的区别在于idref方式会在部署时刻进行验证被引用的bean是否存在;而value的方式只有在client bean被实例化的时候,没准儿在容器部署很久之后才会发现出了问题。同样如果client bean和target bean在同一份xml配置文件中被描述,那么还可以使用<idref local=""/>的方式进行配置。

 

--------------------------------------------------------------

-References to other beans(collaborators)

  <ref>提供以下几类属性:

    <ref bean="abcBean">

    <ref local="abcBean">

    <ref parent="abcBean">

 

  其中bean和local的区别在于:bean的检索范围不同,<ref bean...>的方式,引用范围在同一或者是父容器中,而不需要关心是否在一个xml配置文件中;而local的检索范围是当前xml配置文件(若未能在当前配置文件中找到引用bean定义的时候,会报错)。因此,在确认配置位置在同一配置文件的时候,选用local更为合理,这样可以尽早的定位问题位置。

 

--------------------------------------------------------------

-Inner beans

定义在<property/>或者<constructor-arg/>元素中的<bean />被称作为Inner beans。

 

可以看到Inner bean不需要id或者name;容器会忽略这些值。同样也会忽略scope标签。匿名且其scope总是prototypes,因此无法将其注入其它bean中。

 

--------------------------------------------------------------

-Collections

 

 

集合DI有如下几点说明:

1)自Spring2之后,Spring支持集合的merging功能。对于开发者定义的父集合 <list/>, <map/>, <set/> 或者 <props/>,可以通过元素继承的方式使子集合获取这些配置,并可对其做覆盖配置。也就是说子集合中的元素是父子集合元素merge的结果。

 

 

  其merge的结果为,child集合包含如下元素:

  administrator=administrator@example.com

  sales=sales@example.com

  support=support@example.co.uk (override support)

 

2)Collection Merging的限制:

  首先,只能对同一类集合中的元素进行Merge操作。对于不同类型的集合做Merge操作会抛异常;

  其次,merge属性只能出现在子集合定义中,定义在父集合无效;

  最后,merge功能可在Spring2.0+中进行使用。

 

3)Strongly-typed collection (Java 5+ only)

  代码中,使用JAVA 5+提供的泛型特性,定义集合所含元素的类型。Spring会做类型的自动转换,如:

 

 

 

  其中9.99、2.75以及3.99会被容器自动转换为Float类型。

 

----------------------------------------------------

-Null and empty string values

   

  等价于 Java code: exampleBean.setEmail("")

 

 

  等价于Java code: exampleBean.setEmail(null)

 

----------------------------------------------------

-XML shortcut with the p-namespace

 

 

p-namespace与标准的xml格式比较而言,后者更灵活。例如,若使用p-namespace配置一个以ref结尾的属性名就会产生冲突,然后标准的xml配置方式则不会出现这种冲突情况。

----------------------------------------------------

-Compound property names

使用点运算符,对嵌套属性进行赋值。如:

 

 

foo bean有fred属性,fred属性包含bob属性,而bob属性又包含sammy属性。现对sammy进行赋值为123

要求fred.bob都不为null(否则抛NullPointerException)