# 1.4.2. 详细的依赖关系和配置

如上[一节所述](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-collaborators)，您可以将 bean 属性和构造函数参数定义为对其他托管 bean（协作者）的引用或内联定义的值。为此， Spring 的基于 XML 的配置元数据支持其`<property/>`和元素`<constructor-arg/>`中的子元素类型。

**直接值（基元、字符串等）**

元素`<property/>`的`value`属性将属性或构造函数参数指定为人类可读的字符串表示。Spring 的 [转换服务](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#core-convert-ConversionService-API)用于将这些值从 `String` 转换为属性或参数的实际类型。以下示例显示了正在设置的各种值：

```xml
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <!-- results in a setDriverClassName(String) call -->
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
    <property name="username" value="root"/>
    <property name="password" value="misterkaoli"/>
</bean>
```

以下示例使用[p-namespace](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-p-namespace)进行更简洁的 XML 配置：

```xml
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close"
        p:driverClassName="com.mysql.jdbc.Driver"
        p:url="jdbc:mysql://localhost:3306/mydb"
        p:username="root"
        p:password="misterkaoli"/>

</beans>
```

前面的 XML 更简洁。但是，拼写错误是在运行时而不是设计时发现的，除非您在创建 bean 定义时使用支持自动完善属性功能的 IDE（例如[IntelliJ IDEA](https://www.jetbrains.com/idea/)或[Spring Tools for Eclipse ）。](https://spring.io/tools)强烈推荐这种 IDE 帮助。

您还可以配置`java.util.Properties`实例，如下所示：

```xml
<bean id="mappings"
    class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">

    <!-- typed as a java.util.Properties -->
    <property name="properties">
        <value>
            jdbc.driver.className=com.mysql.jdbc.Driver
            jdbc.url=jdbc:mysql://localhost:3306/mydb
        </value>
    </property>
</bean>
```

Spring 容器通过使用 JavaBeans `PropertyEditor`机制将`<value/>`元素内的文本转换为`java.util.Properties` 实例。这是一个不错的捷径，也是 Spring 团队支持使用嵌套`<value/>`元素而不是`value`属性样式的少数几个地方之一。

**`idref`元素**

`idref`元素只是将容器中另一个 bean 的`id`（字符串值 - 不是引用）传递给`<constructor-arg/>`或元素`<property/>`的一种防错方法 。以下示例显示了如何使用它：

```xml
<bean id="theTargetBean" class="..."/>

<bean id="theClientBean" class="...">
    <property name="targetName">
        <idref bean="theTargetBean"/>
    </property>
</bean>
```

前面的 bean 定义片段与以下片段完全相同（在运行时）：

```xml
<bean id="theTargetBean" class="..." />

<bean id="client" class="...">
    <property name="targetName" value="theTargetBean"/>
</bean>
```

第一种形式比第二种形式更可取，因为使用`idref`标签可以让容器在部署时验证所引用的命名 bean 确实存在。在第二个变体中，不对传递给`client`bean属性`targetName`的值执行验证。只有在实际实例化`client` bean时才会发现拼写错误（很可能是致命的结果） 。如果`client` bean 是一个[原型](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-scopes)bean，那么这个拼写错误和产生的异常可能只有在容器部署很久之后才会被发现。

4.0 bean XSD 不再支持元素上的`local`属性`idref`，因为它不再提供常规`bean`引用的值。在升级到 4.0 架构时将现有`idref local`引用更改为`idref bean` 。

`<idref/>`元素带来价值的常见地方（至少在 Spring 2.0 之前的版本中）是在 bean 定义中的[AOP 拦截器配置中。](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#aop-pfb-1)`ProxyFactoryBean`在指定拦截器名称时使用`<idref/>`元素可以防止您拼错拦截器 ID。

**对其他 Bean 的引用（协作者）**

`ref`元素是`<constructor-arg/>`或`<property/>` 定义元素中的最后一个元素。在这里，您将 bean 的指定属性的值设置为对容器管理的另一个 bean（协作者）的引用。引用的bean是要设置属性的bean的依赖，在设置属性前根据需要进行初始化。（如果协作者是单例 bean，它可能已经被容器初始化。）所有引用最终都是对另一个对象的引用。范围和验证取决于您是否通过`bean`或`parent`属性指定其他对象的 ID 或名称。

通过`<ref/>`标签的`bean`属性指定目标bean是最通用的形式，它允许创建对同一容器或父容器中的任何bean的引用，而且不用管它是否在同一个XML文件中。属性 `bean`的值可以与目标bean 的属性`id`相同，或者与目标bean 的属性`name`中的值之一相同。以下示例显示了如何使用`ref`元素：

```xml
<ref bean="someBean"/>
```

通过属性`parent`指定目标 bean会创建对当前容器的父容器中的 bean 的引用。`parent`属性的值可以与目标 bean 的`id`属性或目标 bean 的属性`name`中的值之一相同。目标 bean 必须在当前 bean 的父容器中。您应该使用此 bean 引用变体，主要是当您具有容器层次结构并且希望使用与父 bean 同名的代理将现有 bean 包装在父容器中时。以下一对清单显示了如何使用`parent`属性：

```xml
<!-- in the parent context -->
<bean id="accountService" class="com.something.SimpleAccountService">
    <!-- insert dependencies as required 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>
```

4.0 bean XSD 不再支持元素上的`local`属性`ref`，因为它不再提供常规`bean`引用的值。在升级到 4.0 架构时需要更改现有`ref local`引用到`ref bean` 。

**内部Bean**

`<property/>`或`<constructor-arg/>`元素中的`<bean/>`元素定义了一个内部 bean，如以下示例所示：

```xml
<bean id="outer" class="...">
    <!-- instead of using a reference to a target bean, simply define the target bean inline -->
    <property name="target">
        <bean class="com.example.Person"> <!-- this is the inner bean -->
            <property name="name" value="Fiona Apple"/>
            <property name="age" value="25"/>
        </bean>
    </property>
</bean>
```

内部 bean 定义不需要定义的 ID 或名称。如果指定，容器不会使用这样的值作为标识符。容器在创建时也会忽略该`scope`标志，因为内部 bean 始终是匿名的，并且始终使用外部 bean 创建。不可能独立访问内部 bean 或将它们注入到协作 bean 中，而不是注入封闭 bean。

作为一个极端情况，可以从自定义范围接收销毁回调 - 例如，对于包含在单例 bean 中的请求范围内的内部 bean。内部 bean 实例的创建与其包含的 bean 相关联，但销毁回调让它参与请求范围的生命周期。这不是常见的情况。内部 bean 通常只是共享其包含 bean 的范围。

**集合**

`<list/>`、`<set/>`、`<map/>`和`<props/>`元素分别设置 Java `Collection`类型中`List`、`Set`、`Map`的属性和`Properties`参数。以下示例显示了如何使用它们：

```xml
<bean id="moreComplexObject" class="example.ComplexObject">
    <!-- results in a setAdminEmails(java.util.Properties) call -->
    <property name="adminEmails">
        <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 name="someList">
        <list>
            <value>a list element followed by a reference</value>
            <ref bean="myDataSource" />
        </list>
    </property>
    <!-- results in a setSomeMap(java.util.Map) call -->
    <property name="someMap">
        <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 name="someSet">
        <set>
            <value>just some string</value>
            <ref bean="myDataSource" />
        </set>
    </property>
</bean>
```

映射键或值或设置值的值也可以是以下任何元素：

```xml
bean | ref | idref | list | set | map | props | value | null
```

**集合合并**

Spring 容器还支持合并集合。应用程序开发人员可以定义父`<list/>`、`<map/>`、`<set/>`或`<props/>`元素，并让子`<list/>` `<map/>` `<set/>` 或`<props/>`元素继承并覆盖父集合中的值。也就是说，子集合的值是合并父集合和子集合的元素的结果，其中子集合元素覆盖父集合中指定的值。

本节关于合并讨论了父子 bean 机制。不熟悉 parent 和 child bean 定义的读者可能希望在继续之前阅读 [相关部分](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-child-bean-definitions)。

以下示例演示了集合合并：

```xml
<beans>
    <bean id="parent" abstract="true" class="example.ComplexObject">
        <property name="adminEmails">
            <props>
                <prop key="administrator">administrator@example.com</prop>
                <prop key="support">support@example.com</prop>
            </props>
        </property>
    </bean>
    <bean id="child" parent="parent">
        <property name="adminEmails">
            <!-- 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>
```

请注意在`child` bean 定义的`merge=true`属性的`<props/>`元素上使用 `adminEmails`属性。当`child` bean 被容器解析和实例化时，生成的实例有一个`adminEmails` `Properties`集合，其中包含将子集合 `adminEmails`与父`adminEmails`集合合并的结果。以下清单显示了结果：

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

子集合`Properties`的值集从父集合继承所有`<props/>`属性元素，并且子集合的值`support`会覆盖父集合中的值。

这种合并行为同样适用于`<list/>`、`<map/>`和`<set/>` 集合类型。在`<list/>`元素的特定情况下，与`List`集合类型相关联的语义（即`ordered` 值集合的概念）得到维护。父级的值在所有子级列表的值之前。对于`Map`、`Set`和`Properties`集合类型，不存在排序。因此，对于容器内部使用的关联`Map`、`Set`和`Properties`实现类型下的集合类型，没有任何排序语义有效。

**集合合并的限制**

您不能合并不同的集合类型（例如 `Map`和 a `List`）。如果您确实尝试这样做，则会抛出适当的`Exception`。`merge`属性必须在较低的继承的子定义中指定。在父集合定义上指定`merge`属性是多余的，不会导致所需的合并。

**强类型集合**

由于 Java 对泛型类型的支持，您可以使用强类型集合。也就是说，可以声明一个`Collection`类型，使其只能包含（例如）`String`元素。如果使用 Spring 将`Collection`强类型依赖注入到 bean 中，则可以利用 Spring 的类型转换支持，以便强类型实例的`Collection` 元素在添加到`Collection`. 以下 Java 类和 bean 定义显示了如何执行此操作：

```java
public class SomeClass {

    private Map<String, Float> accounts;

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

当`something` bean 的`accounts`属性准备好注入时，强类型`Map<String, Float>`的元素类型的泛型信息可以通过反射获得。因此，Spring 的类型转换基础结构将各种 value 元素识别为`Float` type ，并将字符串值（`9.99`、`2.75`和 `3.99`）转换为实际`Float`类型。

**Null 和空字符串值**

Spring 将属性等的空参数视为空`Strings`参数。以下基于 XML 的配置元数据片段将该`email`属性设置为空 `String`值 ("")。

```xml
<bean class="ExampleBean">
    <property name="email" value=""/>
</bean>
```

前面的示例等效于以下 Java 代码：

```java
exampleBean.setEmail("");
```

`<null/>`元素处理`null`值。以下清单显示了一个示例：

```xml
<bean class="ExampleBean">
    <property name="email">
        <null/>
    </property>
</bean>
```

上述配置等价于以下 Java 代码：

```java
exampleBean.setEmail(null);
```

**带有 p 命名空间的 XML 快捷方式**

p-namespace 允许您使用`bean`元素的属性（而不是嵌套 `<property/>`元素）来描述协作 bean 或两者的属性值。

Spring 支持[带有命名空间](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#xsd-schemas)的可扩展配置格式，它基于 XML 模式定义。本章讨论的`beans`配置格式在 XML Schema 文档中定义。但是，p-namespace 没有在 XSD 文件中定义，仅存在于 Spring 的核心中。

以下示例显示了解析为相同结果的两个 XML 片段（第一个使用标准 XML 格式，第二个使用 p-namespace）：

```xml
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean name="classic" class="com.example.ExampleBean">
        <property name="email" value="someone@somewhere.com"/>
    </bean>

    <bean name="p-namespace" class="com.example.ExampleBean"
        p:email="someone@somewhere.com"/>
</beans>
```

该示例显示了在 bean 定义中调用的 p-namespace 中的一个`email`属性。这告诉 Spring 包含一个属性声明。如前所述，p-namespace 没有架构定义，因此您可以将属性的名称设置为属性名称。

下一个示例包括另外两个 bean 定义，它们都引用了另一个 bean：

```xml
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean name="john-classic" class="com.example.Person">
        <property name="name" value="John Doe"/>
        <property name="spouse" ref="jane"/>
    </bean>

    <bean name="john-modern"
        class="com.example.Person"
        p:name="John Doe"
        p:spouse-ref="jane"/>

    <bean name="jane" class="com.example.Person">
        <property name="name" value="Jane Doe"/>
    </bean>
</beans>
```

此示例不仅包括使用 p 命名空间的属性值，而且还使用特殊格式来声明属性引用。第一个 bean 定义`<property name="spouse" ref="jane"/>`用于创建从 bean `john`到 bean `jane`的引用，而第二个 bean 定义`p:spouse-ref="jane"`用作属性来执行完全相同的操作。在本例中，`spouse`是属性名称，而该`-ref`部分表示这不是直接值，而是对另一个 bean 的引用。

p 命名空间不如标准 XML 格式灵活。例如，声明属性引用的格式与以 结尾的属性冲突`Ref`，而标准 XML 格式则不会。我们建议您仔细选择您的方法并将其传达给您的团队成员，以避免生成同时使用所有三种方法的 XML 文档。

**带有 c 命名空间的 XML 快捷方式**

[与带有 p-namespace 的 XML Shortcut](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-p-namespace)类似，在 Spring 3.1 中引入的 c-namespace 允许内联属性来配置构造函数参数，而不是嵌套`constructor-arg`元素。

以下示例使用`c:`命名空间执行与 [基于构造函数的依赖注入](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-constructor-injection)相同的操作：

```xml
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:c="http://www.springframework.org/schema/c"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="beanTwo" class="x.y.ThingTwo"/>
    <bean id="beanThree" class="x.y.ThingThree"/>

    <!-- traditional declaration with optional argument names -->
    <bean id="beanOne" class="x.y.ThingOne">
        <constructor-arg name="thingTwo" ref="beanTwo"/>
        <constructor-arg name="thingThree" ref="beanThree"/>
        <constructor-arg name="email" value="something@somewhere.com"/>
    </bean>

    <!-- c-namespace declaration with argument names -->
    <bean id="beanOne" class="x.y.ThingOne" c:thingTwo-ref="beanTwo"
        c:thingThree-ref="beanThree" c:email="something@somewhere.com"/>

</beans>
```

命名空间使用与通过名称设置构造函数参数`c:`相同的约定`p:`（bean 引用的`-ref`后缀）。同样，它需要在 XML 文件中声明，即使它没有在 XSD 模式中定义（它存在于 Spring 核心中）。

对于构造函数参数名称不可用的极少数情况（通常是在编译字节码时没有调试信息），您可以使用回退到参数索引，如下所示：

```xml
<!-- c-namespace index declaration -->
<bean id="beanOne" class="x.y.ThingOne" c:_0-ref="beanTwo" c:_1-ref="beanThree"
    c:_2="something@somewhere.com"/>
```

由于 XML 语法，索引表示法需要存在前导`_`，因为 XML 属性名称不能以数字开头（即使某些 IDE 允许这样做）。相应的索引符号也可用于`<constructor-arg>`元素，但不常用，因为声明的简单顺序通常在那里就足够了。

实际上，构造函数解析 [机制](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-ctor-arguments-resolution)在匹配参数方面非常有效，因此除非您确实需要，否则我们建议在整个配置中使用名称表示法。

**复合属性名称**

您可以在设置 bean 属性时使用复合或嵌套属性名称，只要路径的所有组件（最终属性名称除外）都不是`null`. 考虑以下 bean 定义：

```xml
<bean id="something" class="things.ThingOne">
    <property name="fred.bob.sammy" value="123" />
</bean>
```

`Something bean` 有一个`fred`属性，该属性有一个 `bob` 属性，该属性有一个 `sammy` 属性，并且最终的 `sammy` 属性被设置为值 `123`。为了使其正常工作，`something` 的 `fred` 属性和 `bob` 属性bean 构造完成后，`fred` 的值不能为 `null`。否则，将引发 `NullPointerException`。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://doc.shiker.tech/spring-he-xin-gong-neng/1.ioc-rong-qi-he-bean-jian-jie/1.4.-yi-lai-xiang/1.4.2.-xiang-xi-de-yi-lai-guan-xi-he-pei-zhi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
