5、Bean的自动装配
- 自动装配是Spring满足bean依赖一种方式
- Spring会在上下文中自动寻找,并且自动给bean装配属性
在Spring中有三种装配的方式
- 在xml中显示的配置
- 在Java中显示配置
- 隐式的自动装配bean【重点】
5.1、测试
1.环境搭建
- 一个人有两个宠物!
5.2、ByName自动装配
<bean id="cat" class="com.oy.pojo.Cat" />
<bean id="dog" class="com.oy.pojo.Dog" />
<!--
byName:会自动在容器上下文中查找,和直接对象set方法后面的值对应的bean Id,根据bean标签中的id查找
-->
<bean id="people" class="com.oy.pojo.People" autowire="byName" >
<property name="name" value="小欧阳" />
</bean>
2.3、ByType自动转配
<bean id="cat" class="com.oy.pojo.Cat" />
<bean id="dog" class="com.oy.pojo.Dog" />
<!--
byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean,根据bean标签中的class查找
-->
<bean id="people" class="com.oy.pojo.People" autowire="byType" >
<property name="name" value="小欧阳" />
</bean>
小结:
- byName的时候,需要保证所以bean的ID唯一,并且这个bean需要和自动注入的属性的set方法的值一致
- byType的时候,需要保证所以bean的class唯一,并且这个bean需要和自动注入的属性的类型一致
5.3、使用注解实现自动装配
jdk1.5支持注解,spring 2.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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启注解支持-->
<context:annotation-config/>
</beans>
@Autowired
直接在属性上使用即可!也可以在set方式上使用!
使用@Autowired我们可以不用编写set方法了,前提是你这个自动装配的属性在IOC(Spring)容器中存在,且符合名字byName
科普:
@Nullable 字段标记了这个注解,说明这个字段可以为null
public @interface Autowired {
boolean required() default true;
}
测试代码
//如果显示定义了Autowired的request属性为false,说明这个对象可以为null,否则不允许为空
@Autowired(required = false)
@Qualifler(配合@Autowired使用)
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成时,我们可以使@Qualifler(value=“xxxx”)去配合@Autowired的使用,去指定一个唯一的bean对象
@Autowired
//配合Autowired使用指定实现一个bean装配的id值,在有多个id时使用
@Qualifier(value = "cat222")
private Cat cat;
@Autowired
@Qualifier(value = "dog222")
private Dog dog;
private String name;
@Resource注解
public class People {
//name为指定一个bean装配的id,指定一个唯一的bean对象
@Resource(name = "cat2")
private Cat cat;
@Resource
private Dog dog;
private String name;
小结:
@Resource和**@Autowired**的区别
-
相同点:
- 都是用来自动装配的,都可以放在属性字段上
-
不同点:
-
@Autowired通过byType的方式实现,而且必须要求这个对象存在【常用】
-
@Resource默认通过byName的方式实现,如果找不到名字,则通过byTypes实现!如果两个找不到的情况下就报异常【常用】
-
执行顺序不同:@Autowired通过byType的方式实现。@Resource默认通过byName的方式实现
-
@Component
- 组件,放在类上,说明这个类被Spring管理了,就是所谓的bean
@Value
- 相当于在xml文件中使用标签为变量赋值一样
//等价于:<bean id="user" class="com.oy.pojo.User">
//@Component 组件
@Component
public class User {
//相当于:<property name="name" value="欧阳"/>
@Value("欧阳")
public String name;
}
@Scope
- 配置单例或者原型模式
@Component
@Scope("singleton")
public class User {
//相当于:<property name="name" value="欧阳"/>
@Value("欧阳")
public String name;
}