📜  春季-Bean自动装配

📅  最后修改于: 2020-11-11 07:03:20             🧑  作者: Mango


您已经了解了如何使用元素声明bean以及如何使用XML配置文件中的元素注入

Spring容器可以自动装配协作bean之间的关系,而无需使用元素,这有助于减少您为基于Spring的大型应用程序编写的XML配置的数量。

自动装配模式

以下是自动装配模式,可用于指示Spring容器使用自动装配进行依赖项注入。您可以使用元素的autowire属性为bean定义指定自动装配模式。

Sr.No Mode & Description
1 no

This is default setting which means no autowiring and you should use explicit bean reference for wiring. You have nothing to do special for this wiring. This is what you already have seen in Dependency Injection chapter.

2 byName

Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file.

3 byType

Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exists, a fatal exception is thrown.

4 constructor

Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.

5 autodetect

Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.

您可以使用byType构造函数自动装配模式来连接数组和其他类型集合。

自动装配的局限性

当在项目中一致使用自动装配时,自动装配效果最佳。如果通常不使用自动装配,则开发人员仅使用自动装配来连接一个或两个bean定义可能会造成混淆。虽然,自动装配可以大大减少指定属性或构造函数参数的需要,但是在使用它们之前,您应该考虑自动装配的局限性和缺点。

Sr.No. Limitations & Description
1

Overriding possibility

You can still specify dependencies using and settings which will always override autowiring.

2

Primitive data types

You cannot autowire so-called simple properties such as primitives, Strings, and Classes.

3

Confusing nature

Autowiring is less exact than explicit wiring, so if possible prefer using explict wiring.