SpringXML方式配置bean的自动装配autowire
Spring的自动装配,也就是定义bean的时候让spring自动帮你匹配到所需的bean,而不需要我们自己指定了。
例如:
User实体类里面有一个属性role
1 2 3 4 5 6 7 | public class User { private int id; private String username; private String password; private Role role; /*****省略get and set****/} |
在我们的applicationConext.xml文件里,假如有两个role对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?xml version="1.0" encoding="UTF-8"?> xsi:schemaLocation="http://www.springframework.org/schema/beans <bean id="role" class="com.fz.entity.Role"></bean> <bean id="role1" class="com.fz.entity.Role"></bean> <bean name="user" class="com.fz.entity.User" scope="prototype"> <property name="role" ref="role"></property> </bean></beans> |
此时<property name="role" ref="role"></property>找到的就是第一个role对象,但是在bean上配置上了autowire之后,则可以不用写<property name="role" ref="role"></property>这个属性了。则是如下的写法:
1 2 3 4 5 6 7 8 9 10 11 | <?xml version="1.0" encoding="UTF-8"?> xsi:schemaLocation="http://www.springframework.org/schema/beans <bean id="role1" class="com.fz.entity.Role"></bean> <bean id="role2" class="com.fz.entity.Role"></bean> <bean name="user" class="com.fz.entity.User" scope="prototype" autowire="default"> </bean></beans> |
autowire的意思就是spring帮你匹配容器里的bean,而匹配规则有如下几种

default:如果在bean上指定了default,则它会去beans标签上去找default-autowire属性
no:不匹配,但是bean必须定义ref元素
byName:根据名字匹配(如果容器里没有该name的bean,则该属性为null)
byType:根据类型匹配(如果同时找多个相同类型的bean,则报错)
constructor:根据构造器匹配(很少使用)
总结:
1、autowire可以写在bean上,也可以写在根元素beans上(写在beans则表示所有的bean都按此规则来自动匹配)
<bean autowire="byName"> <beans autowire="byName">

浙公网安备 33010602011771号