Spring5 08 注解实现自动装配

8.1 注解实现自动装配


  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

在这里插入图片描述
在这里插入图片描述
@ResourceJava 的原生态注解,也可以实现 自动装填。可以匹配 唯一的 类型 或 有一个唯一的 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”)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值