8.1 注解实现自动装配
- 在 xml 文件里 加入
<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"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="people" class="top.muquanyu.pojo.People"></bean>
<bean id="dog" class="top.muquanyu.pojo.Dog"></bean>
<bean id="cat" class="top.muquanyu.pojo.Cat"></bean>
<context:annotation-config></context:annotation-config>
</beans>
注解自动装配,装配的 是 已有的 bean,当然 对应的 id 必须是 byName 形式的。
@AutoWired(require = false)
:也可以让其 为空 赋值,只要 require = fasle 就可以。
@Nullable
:可以 让这个 属性 为 null 值。
@Qualifier
:通过 id 选择 一个 bean
@Resource
:Java 的原生态注解,也可以实现 自动装填。可以匹配 唯一的 类型 或 有一个唯一的 bean 的 id 符合 byName 规范。它的优先级 比 Spring 的 AutoWired 高
下面 就是 不唯一的情况,类型 都是一样的,但是 有俩 dog 的 bean 就会 报错。
改良后如下:可以删除 一个 dog 的 bean 就能解决问题。
也可以用 下面的 通过 id 找到 bean 解决上述问题。
Resource(name = "bean的id")
:根据 id 找到 待自动装填的 bean,然后 进行 装填。
8.2 小总结
@Resource
和 @Autowired
区别:
- 都是用来 自动装配 已有的 bean 的。都可以 放在 属性字段上 来使用。
- @Autowired 直接通过 byType 方式 来 探索找到 bean 然后 进行 装配。如果找不到,再找 byName 名字。
- @Resource 默认是 通过 byName 方式 去实现,如果找不到 符合 byName 的,就 用 byType 实现!如果两个都找不到,那肯定就报错了。
- @Autowired 想指定 一个 id 装配的话,必须搭配 @Qualifier(value = “id”)