spring学习(七、bean的自动装配)
七、bean的自动装配
- 自动装配是Spring满足Bean依赖的一种方式
- Spring会在上下文中自动寻找,并自动给bean装配属性
在Spring中有三种转配的方式
- 在xml中显示的配置
- 在java中显示的配置
- 隐式的自动装配【重要】
1.测试
环境搭建:一个人有两个宠物
2.ByName自动装配
<bean id="cat" class="com.lzt.pojo.Cat"/>
<bean id="dog" class="com.lzt.pojo.Dog"/>
<!--
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanId。
-->
<bean id="people" class="com.lzt.pojo.People" autowire="byName">
<property name="name" value="溜溜"/>
</bean>
3.ByType自动装配
<bean id="cat" class="com.lzt.pojo.Cat"/>
<bean class="com.lzt.pojo.Dog"/><!--可以省略id-->
<!--
byName:会自动在容器上下文中查找,和自己对象属性类型相同的bean。
-->
<bean id="people" class="com.lzt.pojo.People" autowire="byType">
<property name="name" value="溜溜"/>
</bean>
小结:
- byName的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性set方法一致
- byType的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的类型一致
4.使用注解开发
jdk1.5支持,spring从2.5开始支持注解
The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.
使用注解须知:
-
导入约束:context约束
-
配置注解的支持: context:annotation-config/ 【重要】
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> </beans>
@Autowired 【自动注入】
直接在属性或set方法上使用即可
如果@Autowired加在属性上可以不写set方法,前提是这个自动装配的属性在IOC(Spring)容器中存在,且符合名字byname!
@Autowired
private Cat cat;
@Autowired
private Dog dog;
科普:
@Nullable 字段标记了这个注解,说明这个字段可以为null
//如果显示定义了Autowired的required的属性为false,说明这个值可以为null,否则不允许为空
@Autowired(required = false)
private Cat cat;
public @interface Autowired {
boolean required() default true;
}
注意:如果@Autowired的环境比较复杂,byname和bytype都不能找到具体的对象时,可以使用@Qualifier(value = "xxx")配置@Autowired的使用,指定唯一的bean对象注入!
@Autowired
@Qualifier(value = "dog")
private Dog dog;
@Resource:和@Autowired功能类似
@Resource(name = "cat")
private Cat cat;
小结
@Autowired与@Resource异同:
- @Autowired与@Resource都可以用来装配bean。都可以写在字段上,或写在setter方法上。
- @Autowired默认按类型装配(属于spring规范),默认情况下必须要求依赖对象必须存在,如果要允许null 值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用
- @Resource(属于J2EE复返),默认按照名称进行装配,名称可以通过name属性进行指定。如果没有指定name属性,当注解写在字段上时,默认取字段名进行按照名称查找,如果注解写在setter方法上默认取属性名进行装配。 当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。
它们的作用相同都是用注解方式注入对象,但执行顺序不同。@Autowired先byType,@Resource先byName。

浙公网安备 33010602011771号