什么是自动装配?
自动装配就是让应用程序上下文为你找出依赖项的过程。说的通俗一点,就是Spring会在上下文中自动查找,并自动给bean装配与其关联的属性!
spring中实现自动装配的方式有两种,一种是通过xml文件、另一种是通过注解。下面将为大家介绍这两种方式实现自动装配。
为了更简单的让大家理解,我们通过例子来说明:
有以下三个实体类,People类,Dog类,Cat类,分别代表人、狗、猫。人养了一只狗和一只猫,猫和狗都会叫。
public class Cat {
public void shout(){
System.out.println("miao~");
}
}
public class Dog {
public void shout(){
System.out.println("wang wang~");
}
}
public class Peopel {
private Cat cat;
private Dog dog;
private String 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;
}
@Override
public String toString() {
return "Peopel{" +
"cat=" + cat +
", dog=" + dog +
", name='" + name + '\'' +
'}';
}
}
手动装配
讲自动装配之前,我们先来说一下手动装配,手动装配又是什么?手动装配就是手动的将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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="cat" class="com.kuang.pojo.Cat"/>
<bean id="dog" class="com.kuang.pojo.Dog"/>
<bean id="people" class="com.kuang.pojo.Peopel">
<property name="name" value="张三"/>
<property name="cat" ref="cat"/>
<property name="dog" ref="dog"/>
</bean>
</beans>
方式一:通过xml文件实现自动装配
我们只需要在xml配置文件中的bean标签中加入一个属性autowire即可,例如:
<bean id="people" class="com.kuang.pojo.Peopel" autowire="byName">
<property name="name" value="张三"/>
</bean>
使用autowire关键字声明bean的自动装配方式。其可选值为byName、byType、constructor,default,no;这里讲前边两个。
1.byName
设置autowire属性为byName,那么Spring会根据class属性找到实体类,然后查询实体类中所有setter方法的名字,根据setter方法后面的名字(例如SetDog,则setter方法后面的名字为dog)再到配置文件中寻找一个与该名字相同id的Bean,注入进来。如图:
参考 博客: https://www.cnblogs.com/bear7/p/12531016.html