Spring Beans自动装配

前面已经学会如何使用的<bean>元素来声明bean和注入<bean>,通过使用在XML配置文件<constructor-arg>和<property>元素。

Spring容器可以自动装配相互协作bean之间的关系,这有助于减少对XML配置,而无需编写一个大的基于Spring应用程序的较多的<constructor-arg>和<property>元素。

 

自动装配模式:

有下列自动装配模式,可用于指示Spring容器使用自动装配依赖注入。使用<bean/>元素的autowire属性为一个bean定义中指定自动装配模式。

模式 描述
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.
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.
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 typematches with exactly one of the beans name in configuration file. If more than one such beans exists, a fatal exception is thrown.
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.
autodetect Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.

可以使用类型和constructor自动装配模式来连接数组和其他类型化的集合。

 

自动装配的局限性:

自动装配最好效果是它始终在一个项目中使用。如果自动装配不一般的使用,它可能会被混淆为开发人员可以使用它来连接只有一个或两个bean定义。不过,自动装配可以显著减少需要指定属性或构造器参数,但你应该使用它们之前考虑自动装配的局限性和缺点。

限制 描述
压倒一切的可能性 可以使用<constructor-arg>和<property>设置总是覆盖自动装配还指定依赖关系。
原始数据类型 不能自动装配所谓的简单类型包括基本类型,字符串和类。
混乱的本质 自动装配比显式装配确切的少,所以如果可能的话可以使用显式的连接。