Autowiring Collaborators 自动装配合作者
The Spring container can autowire relationships between collaborating beans. You can let Spring resolve collaborators (other beans) automatically for your bean by inspecting the contents of the ApplicationContext
. Autowiring has the following advantages:
Spring容器可以自动装配协作bean之间的关系。通过检查ApplicationContext的内容,可以让Spring为bean自动解析协作者(引用的其他bean)。自动装配具有以下优点:
Autowiring can significantly reduce the need to specify properties or constructor arguments. (Other mechanisms such as a bean template discussed elsewhere in this chapter are also valuable in this regard.)
自动装配可以显著减少指定属性或构造函数参数的需要。(本章其他部分讨论的其他机制(如bean模板)在这方面也很有价值。)
Autowiring can update a configuration as your objects evolve. For example, if you need to add a dependency to a class, that dependency can be satisfied automatically without you needing to modify the configuration. Thus autowiring can be especially useful during development, without negating the option of switching to explicit wiring when the code base becomes more stable.
自动装配可以随着对象的发展而更新配置。例如,如果需要向类添加依赖项,则无需修改配置即可自动满足该依赖项。因此,在开发过程中,autowiring 尤其有用,而不必在代码库变得更稳定时切换到显式连接。
When using XML-based configuration metadata (see Dependency Injection), you can specify the autowire mode for a bean definition with the autowire
attribute of the <bean/>
element. The autowiring functionality has four modes. You specify autowiring per bean and can thus choose which ones to autowire. The following table describes the four autowiring modes:
当使用基于XML的配置元数据(请参见依赖注入)时,可以使用<bean/>
元素的autowire
属性为bean定义指定autowire模式。自动装配功能有四种模式。您可以为每个bean指定自动装配,因此可以选择要自动装配的bean。下表介绍了四种自动装配模式:
Mode | Explanation |
---|---|
no |
(Default) No autowiring. Bean references must be defined by ref elements. Changing the default setting is not recommended for larger deployments, because specifying collaborators explicitly gives greater control and clarity. To some extent, it documents the structure of a system. |
(默认)无自动装配。Bean引用必须由ref元素定义。对于较大的部署,不建议更改默认设置,因为显式指定协作者可以提供更好的控制和清晰度。在某种程度上,它记录了一个系统的结构。 | |
byName |
Autowiring by property name. Spring looks for a bean with the same name as the property that needs to be autowired. For example, if a bean definition is set to autowire by name and it contains a master property (that is, it has a setMaster(..) method), Spring looks for a bean definition named master and uses it to set the property. |
按特性名称自动装配。Spring寻找一个与需要自动装配的属性同名的bean。例如,如果一个bean定义被设置为autowire by name,并且它包含一个master属性(也就是说,它有一个setMaster(..)方法),那么Spring会查找名为master的bean定义并使用它来设置属性。 | |
byType |
Lets a property be autowired if exactly one bean of the property type exists in the container. If more than one exists, a fatal exception is thrown, which indicates that you may not use byType autowiring for that bean. If there are no matching beans, nothing happens (the property is not set). |
如果容器中恰好存在该属性类型的一个bean,则允许该属性自动实现。如果存在多个,就会抛出一个致命异常,这表明您不能对该bean使用byType自动装配。如果没有匹配的bean,则什么也不会发生(没有设置属性)。 | |
constructor |
Analogous to byType but applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised. |
类似于byType,但适用于构造函数参数。如果容器中没有构造函数参数类型的确切bean,就会引发致命错误。 |
With byType
or constructor
autowiring mode, you can wire arrays and typed collections. In such cases, all autowire candidates within the container that match the expected type are provided to satisfy the dependency. You can autowire strongly-typed Map
instances if the expected key type is String
. An autowired Map
instance’s values consist of all bean instances that match the expected type, and the Map
instance’s keys contain the corresponding bean names.
使用byType
或构造函数自动装配模式,您可以连接数组和类型化集合。在这种情况下,提供容器中与预期类型匹配的所有自动装配候选对象来满足依赖关系。如果期望的键类型是String
,您可以自动连接强类型映射实例。自动生成的映射实例的值由与预期类型匹配的所有bean实例组成,映射实例的键包含相应的bean名称。
Limitations and Disadvantages of Autowiring 自动装配的局限性和缺点
Autowiring works best when it is used consistently across a project. If autowiring is not used in general, it might be confusing to developers to use it to wire only one or two bean definitions.
自动装配在项目中一致使用时工作得最好。如果自动装配没有被普遍使用,那么使用它来连接一个或两个bean定义可能会使开发人员感到困惑。
Consider the limitations and disadvantages of autowiring:
考虑自动装配的局限性和缺点:
Explicit dependencies in
property
andconstructor-arg
settings always override autowiring. You cannot autowire simple properties such as primitives,Strings
, andClasses
(and arrays of such simple properties). This limitation is by-design.属性和构造参数设置中的显式依赖关系总是覆盖自动装配。您不能自动连接简单属性,如原语、字符串和类(以及此类简单属性的数组)。这种限制是设计出来的。
Autowiring is less exact than explicit wiring. Although, as noted in the earlier table, Spring is careful to avoid guessing in case of ambiguity that might have unexpected results. The relationships between your Spring-managed objects are no longer documented explicitly.
自动装配不如显式装配精确。不过,正如前面的表中所指出的,Spring小心地避免猜测可能会产生意外结果的歧义。spring管理对象之间的关系不再被明确地记录。
Wiring information may not be available to tools that may generate documentation from a Spring container.
连接信息对于可能从Spring容器生成文档的工具来说可能是不可用的。
Multiple bean definitions within the container may match the type specified by the setter method or constructor argument to be autowired. For arrays, collections, or
Map
instances, this is not necessarily a problem. However, for dependencies that expect a single value, this ambiguity is not arbitrarily resolved. If no unique bean definition is available, an exception is thrown.容器中的多个bean定义可能与要自动实现的setter方法或构造函数参数指定的类型相匹配。对于数组、集合或映射实例,这不一定是个问题。但是,对于期望使用单个值的依赖项,这种模糊性不能任意解决。如果没有可用的唯一bean定义,则抛出异常。
In the latter scenario, you have several options:
在后一种情况下,您有几个选项:
Abandon autowiring in favor of explicit wiring.
放弃自动装配,支持显式。
Avoid autowiring for a bean definition by setting its
autowire-candidate
attributes tofalse
, as described in the next section.通过将一个bean定义的自动装配候选属性设置为false来避免自动装配,如下一节所述。
Designate a single bean definition as the primary candidate by setting the
primary
attribute of its<bean/>
element totrue
.通过将单个bean定义的<bean/>元素的
primary
属性设置为true,将其指定为主候选bean定义。Implement the more fine-grained control available with annotation-based configuration, as described in Annotation-based Container Configuration.
使用基于注释的配置实现更细粒度的控制,如在基于注释的容器配置中所述。
Excluding a Bean from Autowiring 不包括自动装配的bean
On a per-bean basis, you can exclude a bean from autowiring. In Spring’s XML format, set the autowire-candidate
attribute of the <bean/>
element to false
. The container makes that specific bean definition unavailable to the autowiring infrastructure (including annotation style configurations such as @Autowired
).
在每个bean的基础上,您可以从自动装配中排除一个bean。在Spring的XML格式中,将<bean/>元素的自动装配autowire-candidate
属性设置为false。容器使得特定的bean定义对自动装配基础设施不可用(包括注释风格配置,如@Autowired)。
The autowire-candidate attribute is designed to only affect type-based autowiring. It does not affect explicit references by name, which get resolved even if the specified bean is not marked as an autowire candidate. As a consequence, autowiring by name nevertheless injects a bean if the name matches. |
|
---|---|
autowire-candidate属性被设计为只影响基于类型的自动装配。它不影响按名称的显式引用,即使指定的bean没有标记为自动装配(autowire-candidate=false ),也会解析显式引用。因此,如果名称匹配,按名称自动装配仍然会注入一个bean。 |
You can also limit autowire candidates based on pattern-matching against bean names. The top-level <beans/>
element accepts one or more patterns within its default-autowire-candidates
attribute. For example, to limit autowire candidate status to any bean whose name ends with Repository
, provide a value of *Repository
. To provide multiple patterns, define them in a comma-separated list. An explicit value of true
or false
for a bean definition’s autowire-candidate
attribute always takes precedence. For such beans, the pattern matching rules do not apply.
您还可以基于对bean名称的模式匹配来限制自动连接候选项。顶级的<beans/>元素在其default-autowire-candidates
属性中接受一个或多个模式。例如,要将自动装配候选状态限制为名称以Repository结尾的任何bean,可以提供一个值*Repository。要提供多个模式,请在逗号分隔的列表中定义它们。bean定义的自动候选属性的显式值true或false总是优先(高于容器级别的default-autowire-candidates)。对于这样的bean,模式匹配规则不适用。
These techniques are useful for beans that you never want to be injected into other beans by autowiring. It does not mean that an excluded bean cannot itself be configured by using autowiring. Rather, the bean itself is not a candidate for autowiring other beans.
这些技术对于那些您永远不希望通过自动装配被注入到其他bean中的bean非常有用。这并不意味着被排除的bean本身不能使用自动装配进行配置。相反,该bean本身不是自动装配其他bean的候选对象。
下一节:Method Injection 方法注入