Bean的自动装配
- 自动装配是Spring满足bean依赖的一种方式
- Spring会在上下文中自动寻找,并自动给bean装配属性
在Spring中有三种装配的方式
- 在xml中显示的配置
- 在java中显示配置
- 隐式的自动装配bean【重要】
测试
环境搭建:一个人两个宠物
ByName自动装配
<!--byName:会自动在容器上下文中查找,和自己对象set方法后边的值对应的beanid-->
<bean id="people" class="com.god.pojo.People" autowire="byName">
<property name="name" value="peng"/>
</bean>
ByType自动装配
<bean id="cat" class="com.god.pojo.Cat" />
<bean id="dog111" class="com.god.pojo.Dog"/>
<!--byName:会自动在容器上下文中查找,和自己对象set方法后边的值对应的beanid
byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean-->
<bean id="people" class="com.god.pojo.People" autowire="byType">
<property name="name" value="peng"/>
</bean>
- ByName时,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致
- ByType时,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致
使用注解实现自动装配
要使用注解须知:
- 导入约束: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自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value="xxx")去配置@Autowired的使用,指定一个唯一的bean对象注入!
public class People {
@Autowired
private Cat cat;
@Autowired
@Qualifier(value = "dog111")
private Dog dog;
private String name;
@Resource
public class People {
@Resource
private Cat cat;
@Resource(name = "dog111")
private Dog dog;
private String name;
@Autowired和@Resource区别:
- 都是用来自动装配的,都可以放在属性字段上
- @Autowired 通过bytype的方式实现,而且必须要求这个对象存在
- @Resource 默认通过byname的方式实现,如果找不到名字,则通过bytype的方式实现
- 执行顺序不同:@Autowired 通过bytype的方式实现;@Resource 默认通过byname的方式实现
@Resource 是 JDK 自带的注解,默认按名称注入,找不到再按类型。比如,给属性起名 userDao,它就会先找 id 是 userDao 的 Bean。
@Autowired 是 Spring 的注解,默认按类型注入,类型多个时得配合 @Qualifier 指定名称。
@Resource 支持 name 和 type 参数,@Autowired 只有 required 参数。
实际开发中,如果想明确指定 Bean 名称,用 @Resource (name="xxx") 更方便,不用额外加 @Qualifier。
浙公网安备 33010602011771号