自动装配

自动装配
一、Bean的自动装配
自动装配说明
自动装配是使用spring满足bean依赖的一种方法

spring会在应用上下文中为某个bean寻找依赖的bean

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

在xml中显式配置;

在java中显式配置;

隐式的bean发现机制和自动装配。

本文主要讲第三种:自动化的装配bean

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

组件扫描:spring会自动发现上下文中所创建的bean

自动装配:spring自动满足bean之间的依赖,也就是我们说的Ioc/DI;

测试环境搭建:
新建一个项目;

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

package com.aishimin.pojo;
​
public class Cat {
    public void shout(){
        System.out.println("猫叫");
    }
}
package com.aishimin.pojo;
​
public class Dog {
    public void shout(){
        System.out.println("狗叫");
    }
}

 

  1. 新建一个用户类People;

    package com.aishimin.pojo;
    ​
    public class People {
        private Cat cat;
        private Dog dog;
        private String name;
    ​
        @Override
        public String toString() {
            return "People{" +
                    "cat=" + cat +
                    ", dog=" + dog +
                    ", name='" + name + '\'' +
                    '}';
        }
    ​
        public Cat getCat() {
            return cat;
        }
    ​
        public void setCat(Cat cat) {
            this.cat = cat;
        }
    ​
        public Dog getDog() {
            return dog;
        }
    ​
        public void setDog(Dog dog) {
            this.dog = dog;
        }
    ​
        public String getName() {
            return name;
        }
    ​
        public void setName(String name) {
            this.name = name;
        }
    }

     

  2. 在Spring中编写配置文件;

    <?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">
    ​
    ​
    ​
        <bean id="cat" class="com.aishimin.pojo.Cat"/>
        <bean id="dog" class="com.aishimin.pojo.Dog"/>
        <bean id="people" class="com.aishimin.pojo.People">
            <property name="name" value="张三"/>
            <property name="cat" ref="cat"/>
            <property name="dog" ref="dog"/>
        </bean>
    ​
    ​
    ​
    ​
        <context:annotation-config/>
    ​
    ​
    </beans>

     

  3. 测试。

    import com.aishimin.pojo.People;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    ​
    public class MyTest {
        @Test
        public void test(){
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
            People people = context.getBean("people", People.class);
            people.getCat().shout();
            people.getDog().shout();
        }
    }

    正常输出,测试环境OK。

    byName

    autowire byName (按名称自动装配)

    在手动配置xml时,会出现字母漏缺和大小写等错误,检查困难,开发效率降低。

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

    测试:

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

      <bean id="cat" class="com.aishimin.pojo.Cat"/>
      <bean id="dog" class="com.aishimin.pojo.Dog"/>
      <bean id="people" class="com.aishimin.pojo.People" autowire="byName">
          <property name="name" value="张三"/>
      </bean>
    2. 再次测试,依旧正常输出!

    3. 将cat的bean id修改成catXXX

    4. 再次测试,执行时报空指针异常:原因是按照byName的执行规则没有找到对于的set方法,真正的setCat没有执行,对象没有初始化,所以调用的时候就会空指针异常。

    小结:

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

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

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

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

    byType

    autowire byType (按类型自动装配)

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

    测试:

    1. 将People的bean配置修改一下:autowire="byType"

      <bean id="cat" class="com.aishimin.pojo.Cat"/>
      <bean id="dog" class="com.aishimin.pojo.Dog"/>
      <bean id="people" class="com.aishimin.pojo.People" autowire="byType">
          <property name="name" value="张三"/>
      </bean>
    2. 测试,正常输出

    3. 再注册一个cat的bean对象,测试。

      <bean id="cat" class="com.aishimin.pojo.Cat"/>
      <bean id="cat2" class="com.aishimin.pojo.Cat"/>
      <bean id="dog" class="com.aishimin.pojo.Dog"/>
      <bean id="people" class="com.aishimin.pojo.People" autowire="byType">
          <property name="name" value="张三"/>
      </bean>

      报错: NoUniqueBeanDefinitionException: No qualifying bean of type 'com.aishimin.pojo.Cat' available: expected single matching bean but found 2: cat,cat2

       

    1. 删除cat2,将cat的bean名称改掉!测试!因为是按照类型装配,所以不会报异常,也不影响最后的结果。

    二、使用注解

    jdk1.5开始支持注解,spring2.5开始全面支持注解。

    准备工作:利用注解方式注入属性。

    1. 在spring配置文件中引入context文件头。

      <?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">
    2. 开启属性的注解支持。

        
       <context:annotation-config/>

    @Autowired

    • Autowired是按类型自动转配的,不支持id匹配.

    • 需要导入 spring-aop的包!

    测试:

    1. 将People类中的set方法去掉,使用@Autowired注解;

      package com.aishimin.pojo;
      ​
      import org.springframework.beans.factory.annotation.Autowired;
      ​
      public class People {
          
          @Autowired
          private Cat cat;
          @Autowired
          private Dog dog;
          private String name;
      ​
          @Override
          public String toString() {
              return "People{" +
                      "cat=" + cat +
                      ", dog=" + dog +
                      ", name='" + name + '\'' +
                      '}';
          }
      ​
          public Cat getCat() {
              return cat;
          }
      ​
      ​
      ​
          public Dog getDog() {
              return dog;
          }
      ​
          public String getName() {
              return name;
          }
      ​
      }
    2. 此时的配置文件;

      <bean id="cat" class="com.aishimin.pojo.Cat"/>
      <bean id="dog" class="com.aishimin.pojo.Dog"/>
      <bean id="people" class="com.aishimin.pojo.People"/>
    3. 测试,成功输出结果。

    @Qualifier

    • @Autowired是根据类型自动装配的,加上@Qualifier则是根据byName的方式自动装配

    • @Quelifier不能单独使用

    测试:

    1. 配置文件修改内容,保证类型存在对象。且名字不为类的默认名字!

      <bean id="cat" class="com.aishimin.pojo.Cat"/>
      <bean id="cat2" class="com.aishimin.pojo.Cat"/>
      <bean id="dog" class="com.aishimin.pojo.Dog"/>
      <bean id="dog2" class="com.aishimin.pojo.Dog"/>
      <bean id="people" class="com.aishimin.pojo.People"/>
    2. 没有加上@Quelifier测试会直接报错

    3. 在属性上添加@Qualifier注解

      @Autowired
      @Qualifier(value = "cat2")
      private Cat cat;
      @Autowired
      @Qualifier(value = "dog2")
      private Dog dog;

    @Resource

    • @Resource如有指定的name属性,先按照该属性进行byName方式查找装配;

    • 其次再进行默认的byName方式进行装配;

    • 如果以上都不成功,则按照byType的方式自动装配;

    • 都不成功,则报异常。

    实体类:

    @Resource(name = "cat2")
    private Cat cat;
    @Resource
    private Dog dog;
    private String name;

    beans.xml

    <bean id="cat" class="com.aishimin.pojo.Cat"/>
    <bean id="cat2" class="com.aishimin.pojo.Cat"/>
    <bean id="dog" class="com.aishimin.pojo.Dog"/>
    <bean id="people" class="com.aishimin.pojo.People"/>

    测试结果:结果正常输出!

    修改配置文件为:

    <bean id="cat" class="com.aishimin.pojo.Cat"/>
    <bean id="dog" class="com.aishimin.pojo.Dog"/>
    <bean id="people" class="com.aishimin.pojo.People"/>

    实体类只保留注解

    @Resource
    private Cat cat;
    @Resource
    private Dog dog;
    private String name;

    测试结果:结果正常输出!

    结论:先进行byName查找,失败;在进行byType查找,成功。

小结:

  1. @Autowired与@Resource都可以用来装配bean。都可以写在字段上,或写在setter方法上。

  2. @Autowired默认按类型装配(属于spring规范),默认情况下必须要求依赖对象必须存在,如果要允许null 值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用

  3. @Resource(属于J2EE复返),默认按照名称进行装配,名称可以通过name属性进行指定。如果没有指定name属性,当注解写在字段上时,默认取字段名进行按照名称查找,如果注解写在setter方法上默认取属性名进行装配。当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。

  4. 它们的作用相同都是用注解方式注入对象,但执行顺序不同。@Autowired先byType,@Resource先byName。

posted @ 2021-02-23 15:33  aishimin  阅读(397)  评论(0)    收藏  举报