Spring学习之七——Bean的自动装配

Bean的自动装配

Spring学习之七——Bean的自动装配

  1. 自动装配是Spring妈祖bean依赖的一种方式
  2. Spring会在上下文中自动寻找,并自动给bean配置属性

在Spring中有三种装配方式

  1. 在xml中显示配置
  2. 在java中显示配置
  3. 隐式的自动装配bean【重要】

1.1、测试

环境搭建:一个人有两个宠物

1.2、自动装配

1.2.1、byName自动装配

<bean id="cat" class="com.Sirius.pojo.Cat"/>
<bean id="dog" class="com.Sirius.pojo.Dog"/>
<!--
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid!
-->
<bean id="person" class="com.Sirius.pojo.Person" autowire="byName">
	<property name="name" value="张三"/>
</bean>

1.2.2、byType自动装配

<bean id="cat" class="com.Sirius.pojo.Cat"/>
<bean id="dog" class="com.Sirius.pojo.Dog"/>
<!--
byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean!
-->
<bean id="person" class="com.Sirius.pojo.Person" autowire="byType">
    <property name="name" value="张三"/>
</bean>

1.2.3、小结

  • byName的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入属性的set方法的值一致!
  • byType的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入属性的类型一致!

1.3、使用注解实现自动装配

  • jdk1.5支持的注解,Spring2.5就支持注解

  • The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.

  • 使用注解须知:

  1. 导入约束:context约束
  2. 配置注解的支持 【重要】
<?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容器中存在,且符合byName!

  • 科普:

@Nullable    字段标记了这个注释,说明这个字段可以为null

如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value = “xxx”)去配置@Autowired的使用,指定
一个唯一的bean对象注入。

@Data
public class Person {
    @Autowired
    @Qualifier(value = "cat123")
    private Cat cat;
    
    @Autowired
    @Qualifier(value = "dog123")
    private Dog dog;
    private String name;
}

@Resource注解

@Data
public class Person {
    @Resource(name = "cat123")
    private Cat cat;

    @Resource
    private Dog dog;
    private String name;
}

小结:

@Autowired 和@Resource 的区别:

  • 都是用来自动装配的,都可以放在属性字段上
  • @Autowired 优先通过byType方式实现,而且必须要求这个对象存在,否则会报错。
  • @Resource 优先通过byName方式实现,如果找不到名字,则通过byType实现,如果两个方式都没用,则会报错。
  • 执行顺序不同:@Autowired 通过byType方式实现,@Resource 通过byName方式实现
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值