Spring中自动装配的含义:
就是指 Spring 容器在不使用 <constructor-arg> 和<property> 标签的情况下,可以自动装配(autowire)相互协作的 Bean 之间的关联关系,将一个 Bean 注入其他 Bean 的 Property 中。
两种方式:
byName:
当一个bean节点带有 autowire byName的属性时。
1.将查找其类中所有的set方法名,例如setCat,获得将set去掉并且首字母小写的字符串,即cat。
2.去spring容器中寻找是否有此字符串名称id的对象。
3.如果有,就取出注入;如果没有,就报空指针异常。
byType:
使用autowire byType首先需要保证:同一类型的对象,在spring容器中唯一。如果不唯一,会报不唯一的异常。
关于其他注解:
1.@Autowired
方式:在xml文件中引入
<context:annotation-config></context:annotation-config>
<context:annotation-config></context:annotation-config>
<bean id="cat2" class="com.openlab.Bean.Cat"></bean>
<bean id="dog" class="com.openlab.Bean.Dog"></bean>
<bean id="users" class="com.openlab.Bean.Users" ></bean>
将User类中的set方法去掉,使用@Autowired注解
@Autowired(required=false) 说明: false,对象可以为null;true,对象必须存对象,不能为null。
2.@Qualifier
<context:annotation-config></context:annotation-config>
<bean id="cat2" class="com.openlab.Bean.Cat"></bean>
<bean id="dog1" class="com.openlab.Bean.Dog"></bean>
<bean id="cat1" class="com.openlab.Bean.Cat"></bean>
<bean id="dog2" class="com.openlab.Bean.Dog"></bean>
<bean id="users" class="com.openlab.Bean.Users" ></bean>
@Autowired是根据类型自动装配的,加上@Qualifier则可以根据byName的方式自动装配
@Qualifier不能单独使用。
@Autowired与@Resource异同:
1. @Autowired与@Resource都可以用来装配bean。都可以写在字段上,或写在setter方法上。
2.@Autowired默认按类型装配(属于spring规范),默认情况下必须要求依赖对象必须存在,如果要允许null 值,可以设置它的required属性为false,
如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用
3.@Resource(属于J2EE复返),默认按照名称进行装配,名称可以通过name属性进行指定。
如果没有指定name属性,当注解写在字段上时,默认取字段名进行按照名称查找,如果注解写在setter方法上默认取属性名进行装配。 当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。
它们的作用相同都是用注解方式注入对象,但执行顺序不同。
@Autowired先byType,@Resource先byName。