7.4.5 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 and constructor-arg settings always override autowiring. You cannot autowire so-called simple properties such as primitives,Strings, and Classes (and arrays of such simple properties). This limitation is by-design.
  •  property 和constructor-arg 中明确的依赖设置总是会重写自动装配.你不能够自动装配所谓的简单属性,例如基本数据类型,Strings, 和 Classes (还有例如简单属性的数组).这是设计上的限制.
  • Autowiring is less exact than explicit wiring. Although, as noted in the above 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 Maps, 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方法和构造器参数指定的类型去自动装配.对于数组,集合,或Maps,这不是一个必要的问题.然而对于依赖是一个单一的值,这种模糊不清的情况下不会随意的去解析.如果获取到了一个不唯一的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 to false as described in the next section.
  • 避免自动装配,通过给一个bean定义设置它的 autowire-candidate 属性为 false ,这个会在下一节讨论.
  • Designate a single bean definition as the primary candidate by setting the primary attribute of its <bean/> element to true.
  • 指定一个单一的bean定义作为primary 候选,通过设置它的 <bean/> 元素的 primary 属性为 true.
  • Implement the more fine-grained control available with annotation-based configuration, as described in Section 7.9, “Annotation-based container configuration”.
  • 实现更细粒度的控制通过基于注解的配置,这个描述在Section 7.9, “Annotation-based container configuration”.

猜你喜欢

转载自blog.csdn.net/weixin_41648566/article/details/80936848