Spring初级:Bean自动的装配

105 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第32天,点击查看活动详

一、概述

自动装配时Spring满足bean依赖的一种方式!Spring会在上下文中自动寻找,并自动给bean装配属性!在Spring中有三种装配的方式:在xml中显示设置、在java中显示配置、隐式的自动装配bean。

二、搭建环境测试

创建实体类

public class People {
    //如果显式定义了required属性为false,说明这个对象可以为null,否则不允许为空
    private Dao dao;

    private Cat cat;
    private String name;

    public Dao getDao() {
        return dao;
    }

    public Cat getCat() {
        return cat;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "People{" +
                "dao=" + dao +
                ", cat=" + cat +
                ", name='" + name + ''' +
                '}';
    }
}
public class Dao {

    public void shout(){
        System.out.println("汪汪~");
    }
}
public class Cat {

    public void shout(){
        System.out.println("喵喵~");
    }
}

编写bean.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
        https://www.springframework.org/schema/beans/spring-beans.xsd


</beans>

ByName自动装配

   <bean id="cat" class="com.zhao.pojo.Cat" />
    <bean id="dao" class="com.zhao.pojo.Dao" />       
		<!--
            byName:会在自动在容器上下文查找,和自己对象set方法后面的值对应的beanid
        -->
    <bean id="people" class="com.zhao.pojo.People" autowire="byName">
        <property name="name" value="小王" />
    </bean>

ByType自动装配

    <bean id="cat" class="com.zhao.pojo.Cat" />
    <bean id="dao" class="com.zhao.pojo.Dao" />

        <!--
            byType:会在自动在容器上下文查找,和自己对象属性相同的bean!
        -->
    <bean id="people" class="com.zhao.pojo.People" autowire="byType">
        <property name="name" value="小王" />
    </bean>

小结:

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

三、使用注解进行Bean装配

第一步:导入约束

<?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">


</beans>

第二步:配置注解的支持

  <context:annotation-config/>

@Autowired

可以直接在属性上使用即可,也可以在set方法上使用!

使用时,可以不用编写Set方法,前提是自动装配的属性在IOC(Spring)容器中,且符合名字byname!

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

public @interface Autowired {

	/**
	 * Declares whether the annotated dependency is required.
	 * <p>Defaults to {@code true}.
	 */
	boolean required() default true;
}

测试使用

public class People {
    //如果显式定义了required属性为false,说明这个对象可以为null,否则不允许为空
    @Autowired(required = false)
    private Dao dao;
    @Autowired
    private Cat cat;
    private String name;
    
    ```
public Dao getDao() {
    return dao;
}

public Cat getCat() {
    return cat;
}

public String getName() {
    return name;
}

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

@Override
public String toString() {
    return "People{" +
            "dao=" + dao +
            ", cat=" + cat +
            ", name='" + name + ''' +
            '}';
}
  }

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

    @Autowired(required = false)
    @Qualifier(value = "dao")
    private Dao dao;
    @Autowired
    @Qualifier(value = "cat")
    private Cat cat;
    private String name;

@Resource注解

public class People {
    @Resource
    private Dao dao;

    @Resource
    private Cat cat;
    
    
    public Dao getDao() {
        return dao;
    }

    public Cat getCat() {
        return cat;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "People{" +
                "dao=" + dao +
                ", cat=" + cat +
                ", name='" + name + ''' +
                '}';
        }
}

小结

@Resource注解和@Autowired的区别:

  • 都是用来自动装配的,都可以放在属性字段上
  • @Autowired通过byType方式实现,必须要求对象存在【常用】
  • @Resource默认通过byname方式实现,如果找不到名字,则通过byType实现!如果两个都找不到,就报错!
  • 执行顺序不同:@Autowired通过byType方式实现,@Resource默认通过byname方式实现