bean的自动装配


Bean的自动装配

  • 自动装配是使用spring满足bean依赖的一种方法
  • spring会在应用上下文中为某个bean寻找其依赖的bean。

Spring中bean有三种装配机制,分别是:

  • 在xml中显式配置;
  • 在java中显式配置;
  • 隐式的bean发现机制和自动装配。

这里我们主要讲第三种:自动化的装配bean。

Spring的自动装配需要从两个角度来实现,或者说是两个操作:

  • 组件扫描(component scanning):spring会自动发现应用上下文中所创建的bean;
  • 自动装配(autowiring):spring自动满足bean之间的依赖,也就是我们说的IoC/DI;

组件扫描和自动装配组合发挥巨大威力,使得显示的配置降低到最少。

推荐使用注解 , 而不使用自动装配xml配置.

测试环境搭建

1、新建一个项目

2、新建两个实体类,Cat Dog 都有一个叫的方法

public class Cat {
    public void bark(){
        System.out.println("miao~");
    }
}
public class Dog {
    public void bark(){
        System.out.println("wang~");
    }
}

3、新建一个用户类 Person

public class Person {

    private String name;
    private Dog dog;
    private Cat cat;
}

4、编写Spring配置文件beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="cat" class="com.allen.pojo.Cat"/>
    <bean id="dog" class="com.allen.pojo.Dog"/>

    <bean id="person" class="com.allen.pojo.Person">
        <property name="name" value="allen"/>
        <property name="cat" ref="cat"/>
        <property name="dog" ref="dog"/>
    </bean>
</beans>

5、测试

public class MyTest {
   @Test
   public void testMethodAutowire() {
       ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
       User user = (User) context.getBean("user");
       user.getCat().shout();
       user.getDog().shout();
  }
}

结果正常输出,环境OK

byName (按名称自动装配)

autowire byName (按名称自动装配)

由于在手动配置xml过程中,常常发生字母缺漏和大小写等错误,而无法对其进行检查,使得开发效率降低。

采用自动装配将避免这些错误,并且使配置简单化。

测试:

1、修改bean配置,增加一个属性 autowire=”byName”

<bean id="cat" class="com.allen.pojo.Cat"/>
<bean id="dog" class="com.allen.pojo.Dog"/>

<!--会自动在上下文中寻找,和自己对象set方法后面的值对应的 bean id-->
<bean id="person" class="com.allen.pojo.Person" autowire="byName">
    <property name="name" value="allen"/>
</bean>

2、再次测试,结果依旧成功输出!

当一个bean节点带有 autowire byName的属性时:

1.将查找其类中所有的set方法名,例如setCat,获得将set去掉并且首字母小写的字符串,即cat。

2.去spring容器中寻找是否有此字符串名称id的对象。

3.如果有,就取出注入;如果没有,就报空指针异常。

注意:注册名称 (id) 一定要对应. 否则按byName规则找不对应set方法,真正的setCat就没执行,对象就没有初始化,所以调用时就会报空指针错误。

byType(按类型自动装配)

autowire byType (按类型自动装配)

使用autowire byType首先需要保证:同一类型的对象,在spring容器中唯一。如果不唯一,会报不唯一的异常。

<!--会自动在上下文中寻找,和自己对象类型相同的bean-->
<bean id="person" class="com.allen.pojo.Person" autowire="byType">
    <property name="name" value="allen"/>
</bean>


使用注解实现 bean 的自动装配

环境准备

  1. 导入约束:context约束

  2. 开启注解的支持 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/>
    
```

@Autowired(适用于单例模式)

Person 类(注意@Autowired的使用位置)

注意:在属性前加上@Nullable,即使属性值为null,也不报空指针异常错误。

public class Person {

    private String name;

    //@Autowired(required = false)允许注解的属性为null,而不报空指针异常
    @Autowired(required = false)
    private Dog dog;
    @Autowired
    private Cat cat;

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public Cat getCat() {
        return cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }

    public String getName() {
        return name;
    }

    //加上@Nullable,允许name为null而不报空指针异常
    public void setName(@Nullable String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "dog=" + dog +
                ", cat=" + cat +
                ", name='" + name + '\'' +
                '}';
    }
}

beans.xml

<?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
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd"
>
    <!-- 开启注解支持-->
    <context:annotation-config/>

    <bean id="cat" class="com.allen.pojo.Cat"/>
    <bean id="dog" class="com.allen.pojo.Dog"/>
    <bean id="person" class="com.allen.pojo.Person"/>

</beans>

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

Person类

public class Person {

    private String name;

    /**
     * import javax.annotation.Resource;
    @Resource(name="dog222")指定了 bean 的 id 为 dog222,
    当有同一个类下的多个对象时,使用@Resource注解
     **/
    @Resource(name="dog222")
    private Dog dog;
    //使用 @Autowired 和 @Qualifier(value="cat222") 相当于 @Resource(name="cat222")
    @Autowired
    @Qualifier(value="cat222")
    private Cat cat;

    //get set toString

}

@Resource(可通过 bean 的 id 选择作用的对象)

Person 类(注意@@Resource的使用位置及用法)

public class Person {

    private String name;

    /**
     * import javax.annotation.Resource;
    @Resource(name="dog222")指定了 bean 的 id 为 dog222,
    当有同一个类下的多个对象时,使用 @Resource注解
     **/
    @Resource(name="dog222")
    private Dog dog;
    @Resource
    private Cat cat;

    //get set toString

}

beans.xml(同一类下有多个对象)

<?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
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd"
>
    <!-- 开启注解支持-->
    <context:annotation-config/>

    <bean id="cat" class="com.allen.pojo.Cat"/>
    <bean id="dog" class="com.allen.pojo.Dog"/>
    <bean id="dog222" class="com.allen.pojo.Dog"/>
    <bean id="person" class="com.allen.pojo.Person"/>

</beans>

注解说明

  • 都是用来自动装配的,都可以放在属性字段上;
  • @Autowired先通过类型(byType)实现,如果有多个类型,再按照name(byName);@Resource先通过名字(byName),再通过类型(byType)实现自动装配;
  • @Autowired 限定名称时需要通过@Qualifier(value=”xxx”)配合使用;
  • @Nullable,允许属性值为 null 而不报空指针异常。

文章作者: Hailong Gao
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Hailong Gao !
评论
  目录