采用传统的XML方式配置Bean组件的关键代码如下所示
<bean id="userMapper" class="edu.cn.dao.UserMapperImpl"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> <bean id="userService" class="edu.cn.dao.UserServiceImpl"> <property name="userMapper" ref="userMapper"/> </bean>
我们通过<property>标签为Bean的属性注入所需的值,当需要维护的Bean组件及需要注入的属性更多时,势必会增加配置的工作量。这时可以使用自动装配。
使用自动装配修改配置代码如下
<bean id="userMapper" class="edu.cn.dao.UserMapperImpl" autowire="byName"/> <bean id="userService" class="edu.cn.dao.UserServiceImpl" autowire="byName"/>
通过设置<bean>元素的autowire属性指定自动装配,代替了通过<property>标签显示指定Bean的依赖关系。由BeanFactory检查XML配置文件的内容,为Bean自动注入依赖关系。
Spring提供了多种自动装配方式,autowire属性常用的取值如下所示
在Spring配置文件中通过<bean>元素的autowire属性可以实现自动装配。但是,如果要配置的Bean很多,每个Bean都配置autowire属性也会很繁琐,可不可以统一设置自动注入而不必分别配置每个Bean呢?
原文:https://www.cnblogs.com/yanguobin/p/11703372.html