自动装配是Spring注入bean依赖的一种方式
Spring会在上下文中自动寻找,并自动给bean装配属性
在Spring中有三种装配的方式
1、在xml中显示的配置
2、在java中显示配置
3、隐式的自动装配*
1、测试
环境搭建:一个人有两个宠物
People,Cat,Dog
2、byName自动装配
<bean id="cat" class="com.kuang.pojo.Cat"></bean> <bean id="dog" class="com.kuang.pojo.Dog"></bean>
<!-- byName: 会自动在容器上下文查找,和自己对象set方法后面的值对应的beanid 例如People对象中的 setDog 则查找 id 为 “Dog” 或 “dog” 的bean --> <bean id="people" class="com.kuang.pojo.People" autowire="byName"> <property name="name" value="Bear"></property> </bean>
3、byType自动装配
<bean class="com.kuang.pojo.Cat"></bean> <bean id="dog111" class="com.kuang.pojo.Dog"></bean>
<!-- bytype: 会自动在容器上下文查找,和自己对象属性相同的bean 甚至不需要id,单xml中 该属性值的个数唯一 --> <bean id="people" class="com.kuang.pojo.People" autowire="byType"> <property name="name" value="Bear"></property> </bean>
4、小结
-
byName的时候,需要保证所有的bean的id唯一,并且这个bean需要和自动注入的属性set方法的值一致
-
byType的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致
5、使用注解实现自动装配
jdk1.5支持的注解,Spring2.5就支持注解了!
要使用注解须知
-
导入约束。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方法上使用!
使用反射的方法实现,就不需要使用set方法,前提是你这个自动装配的属性在IOC(Spring)容器中存在,且符合名字byName
package com.kuang.pojo;
import org.springframework.beans.factory.annotation.Autowired;
public class People {
@Autowired
private Dog dog;
@Autowired
private Cat cat;
private String name;
public Dog getDog() {
return dog;
}
public Cat getCat() {
return cat;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "People{" +
"dog=" + dog +
", cat=" + cat +
", name='" + name + '\'' +
'}';
}
}
6、科普
(1)@Autowired
//如果显示定义了AutoWired的required属性为false,说明这个对象可以为null,否则不可以为空 @Autowired(required = false) private Cat cat;
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value="xxx")取配置@Autowired的使用,指定一个唯一的bean对象注入
(2)@Nullable
@Nullable 字段标识了这个注解,说明这个字段可以为null
例如
public void People {
private String name;
public People(@Nullable String name) {
this.name=name;
}
}
(3)@Resource
public class People {
@Resource(name="cat2")
private Cat cat;
@Resource
private Dog dog;
}
小结:
@Resource和@Autowired的区别
-
都是用来自动装配的,都可以放在属性字段上
-
@Autowired 通过byType的方式实现,而且必须要求这个·对象存在!【常用】
-
@Resource默认通过byName的方式实现,如果找不到名字,则通过ByType实现,如果还找不到,则报错【常用】
-
执行顺序不同:@Autowired 通过byType的方式实现,@Resource默认通过byName的方式实现
902

被折叠的 条评论
为什么被折叠?



