0%

7.Bean的自动装配

7.Bean的自动装配

  • 自动装配是Spring满足Bean依赖的一种方式!
  • Spring会在上下文中自动寻找Bean,自动给Bean装配属性

一共有三种装配方式

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

    7.1测试

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

手动装配xml Bean

1
2
3
4
5
6
7
8
<bean id="cat" class="com.lwj.pojo.Cat"></bean>

<bean id="dog" class="com.lwj.pojo.Dog"></bean>
<bean id="people" class="com.lwj.pojo.People">
<property name="name" value="张三"></property>
<property name="cat" ref="cat"></property>
<property name="dog" ref="dog"></property>
</bean>

7.2ByName自动装配

1
2
3
4
5
 <!--byName会自动在容器上下文中查找,和自己对象化set方法后面的值对应的BeanId!-->
<!--这样就自动吧Dog和Cat装配到People上面引用了-->
<bean id="people" class="com.lwj.pojo.People" autowire="byName">
<property name="name" value="张三"></property>
</bean>

7.3ByType

1
2
3
4
5
<!--byType会自动在容器上下文中查找,和自己对象属性类型相同的Bean!-->
<!--这样就自动吧Dog和Cat装配到People上面引用了-->
<bean id="people" class="com.lwj.pojo.People" autowire="byType">
<property name="name" value="张三"></property>
</bean>

小结:

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

7.4使用注解实现自动装配【重点】

jdk1.5支持的注解,Spring2.5后支持注解

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

要使用注解须知:

  • 导入约束 :context约束

  • 配置注解的支持:context:annotation-config/

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <?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方法上使用!

使用@Aotiowried我们可以不用白那些Set方法了,前提是你这个自动装配的属性在IOC容器中存在,且符合名字byName!

科普:

1
@Nullable  字段标记了这个注解,说明这个字段可以为null
1
2
3
4
5
6
//如果定义了Autowired的required属性为false,说明这个对象可以为空,否则不能为空
@Autowired(required = false)
private Cat cat;
@Autowired
private Dog dog;
private String name;

如果@Autowrided自动装配环境比较复杂,奏定装配无法通过一个注解(@Autowrided)完成的时候,我们可以使用@Qualifier(value = “***”)去配合@Autowrided的使用,来获得唯一一个bean对象注入!

1
2
3
4
5
6
@Autowired()
@Qualifier(value = "dog222")
private Cat cat;
@Autowired
private Dog dog;
private String name;

@Resource【不常用】

使用方法和Aotiowried差不多,不需要Spring框架的支持,是Java自带的。

小结

Aotiowried和Resource的区别:

  • 都是用来自动装配的,都可以放在属性字段上
  • Aotiowried是通过byType的的方式实现,找不到再找byName,而且必须要求这两个对象存在!【常用】
  • Resource默认通过nyName的方式实现,如果找不到名字,则通过byType实现,如果两个都找不到就报错了。