学科分类
目录
SSM框架

自动装配

虽然使用注解的方式装配Bean,在一定程度上减少了配置文件中的代码量,但是也有企业项目中,是没有使用注解方式开发的,那么有没有什么办法既可以减少代码量,又能够实现Bean的装配呢?

答案是肯定的,Spring的<bean>元素中包含一个autowire属性,我们可以通过设置autowire的属性值来自动装配Bean。所谓自动装配,就是将一个Bean自动的注入到到其他Bean的Property中。

autowire属性有5个值,其值及说明如表1所示。

表1 <bean>元素的autowire属性值及说明

属性值 说明
default (默认值) 由<bean>的上级标签<beans>的default-autowire属性值确定。例如<beans default-autowire="byName">,则该<bean>元素中的autowire属性对应的属性值就为byName。
byName 根据属性的名称自动装配。容器将根据名称查找与属性完全一致的Bean,并将其属性自动装配。
byType 根据属性的数据类型(Type)自动装配,如果一个Bean的数据类型,兼容另一个Bean中属性的数据类型,则自动装配。
constructor 根据构造函数参数的数据类型,进行byType模式的自动装配。
no 默认情况下,不使用自动装配,Bean依赖必须通过ref元素定义。

下面通过修改上一节中的案例来演示如何使用自动装配。

(1)修改上一节中的文件UserServiceImpl和文件 UserController,分别在文件中增加类属性的setter方法。

(2)修改上一小节中的配置文件beans6.xml,将配置文件修改成自动装配形式,如文件1所示。

文件1 beans6.xml

 1    <?xml version="1.0" encoding="UTF-8"?>
 2    <beans xmlns="http://www.springframework.org/schema/beans"
 3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 4          xmlns:context="http://www.springframework.org/schema/context"
 5          xsi:schemaLocation="http://www.springframework.org/schema/beans 
 6           http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
 7           http://www.springframework.org/schema/context 
 8      http://www.springframework.org/schema/context/spring-context-4.3.xsd">
 9        <!-- 使用bean元素的autowire属性完成自动装配 -->
 10        <bean id="userDao" 
 11            class="com.itheima.annotation.UserDaoImpl" />
 12        <bean id="userService" 
 13          class="com.itheima.annotation.UserServiceImpl" autowire="byName" />
 14        <bean id="userController" 
 15          class="com.itheima.annotation.UserController" autowire="byName"/>
 16    </beans>

上述配置文件中,用来配置userService和userController的<bean>元素中除了id和class属性外,还增加了autowire属性,并将其属性值设置为byName。默认情况下,配置文件中需要通过ref来装配Bean,但设置了autowire="byName"后,Spring会自动寻找userService Bean中的属性,并将其属性名称与配置文件中定义的Bean做匹配。由于UserServiceImpl中定义了userDao属性及其setter方法,这与配置文件中id为userDao的Bean相匹配,所以Spring会自动的将id为userDao的Bean装配到id为userService的Bean中。

执行程序后,控制台的输出结果如图1所示。

图1 运行结果

从图1可以看出,使用自动装配同样完成了依赖注入。

点击此处
隐藏目录