Spring中使用@Autowired注解进行自动匹配bean

1、前言

Spring中配置文件bean的自动装配有很多种方式,今天在学习中了解了使用注解@Autowired的知识进行bean的装配,下面我谈一谈自己的理解:

2、测试环境介绍

2.1、实体类

  • Cat
package com.my.pojo;

public class Cat {
    public void shout(){
        System.out.println("wang~");
    }
}
  • Dog
package com.my.pojo;

public class Dog {
    public void shout(){
        System.out.println("miao~");
    }
}
  • People
package com.my.pojo;

import org.springframework.lang.Nullable;

public class People {
    private String name;

    //如果给Autowired注解赋值一个参数required(它默认为true)赋值为false,那么这个属性可以为空值
    private Dog dog;
    private Cat cat;

    public String getName() {
        return name;
    }

    public void setName(@Nullable String name) {
        this.name = name;
    }

    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;
    }

    @Override
    public String toString() {
        return "People{" +
                "name='" + name + '\'' +
                ", dog=" + dog +
                ", cat=" + cat +
                '}';
    }
}
  • 测试类
import com.my.pojo.People;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        People people = context.getBean("people", People.class);
        people.getDog().shout();
        people.getCat().shout();
    }
}

3、@Autowired详解

3.1.beans.xml配置

  • beans.xml配置
<bean id="cat" class="com.my.pojo.Cat"/>
<bean id="dog" class="com.my.pojo.Dog"/>
<bean id="people" class="com.my.pojo.People"/>
  • People实体类@Autowired注解
@Autowired
private Dog dog;
@Autowired
private Cat cat;
  • 测试结果
    在这里插入图片描述

3.2、beans.xml配置(变化一)

  • beans.xml配置
<bean id="cat123" class="com.my.pojo.Cat"/>
<bean id="dog123" class="com.my.pojo.Dog"/>
<bean id="people" class="com.my.pojo.People"/>
  • 如果实体类People还使用上面3.1的方式进行注解,那么经过测试,代码可以正常测试,没有报错!

3.1和3.2总结

@Autowired注解工作原理:当使用该注解时,Spring容器自动匹配bean(类对象),首先根据class后面的全限定名进行自动匹配(byType方式);其次就是根据id属性进行自动匹配,id的值是setXx方法中的Xx(byName方式)。
它和@Resource注解的原理相反,@Resource注解先通过byName的方式查找,再通过byType的方式,如果都不成功就会报错。

3.3、beans.xml配置(变化二)

  • beans.xml配置
<bean id="cat456" class="com.my.pojo.Cat"/>
<bean id="cat123" class="com.my.pojo.Cat"/>
<bean id="dog123" class="com.my.pojo.Dog"/>
<bean id="dog456" class="com.my.pojo.Dog"/>
<bean id="people" class="com.my.pojo.People"/>
  • 当出现上述配置情况时,那么使用3.1和3.2那种@Autowired注解已经不能解决了(原因:@Autowired注解已经不能通过id和class属性进行自动匹配了)
  • 会出现类似下面的报错信息
    在这里插入图片描述
  • 解决方法(使用@Qualifier注解来解决)
    @Autowired
    @Qualifier(value = "dog123")
    private Dog dog;
    @Autowired
    @Qualifier(value = "cat123")
    private Cat cat;
  • 通过指定id的方式来解决这种情况!

版权声明:本文为qq_48575500原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。