何为自动装配?
- 之前使用Spring的配置文件为java程序类配置Bean,并为java程序类中的属性赋值.
- 而如果java类中拥有其他类的关联属性,例如一个自定义的关联属性Student,这样的操作都是通过"ref"手工的方式指定赋值的.而自动装配的目的就是由IOC容器为Bean属性自动赋值.
- 普通配置:“p:student-ref=student1”
- student1为bean的id值
<bean id="person7" class="mao.shu.spring.Person"
p:id="123"
p:name="p命名空间测试"
p:balance="500"
p:student-ref="student1">
</bean>
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/654cff920e6cbb5072a59e6ba682ee89.png)
自动装配示例
- 现在有三个java类
- Employee
- Department
- Salary
- 现在Employee类中包含一个Department属性和一个Salary属性
public class Employee {
private Integer id;
private String name;
private Integer age;
private String job;
private Department dept;
private Salary salary;
}
public class Department {
private Integer deptno;
private String dname;
private String loc;
}
public class Salary {
private Integer sid;
private Double baseSalary;
}
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="salary" class="mao.shu.spring.autowrite.Salary"
p:sid="1"
p:baseSalary="5000.5">
</bean>
<bean id="department" class="mao.shu.spring.autowrite.Department"
p:deptno="1290"
p:dname="软件开发部"
p:loc="北京">
</bean>
<bean id="employee" class="mao.shu.spring.autowrite.Employee"
p:id="9527"
p:name="xiemaoshu"
p:age="22"
p:job="程序员"
autowire="byName">
</bean>
</beans>
package mao.shu.spring.autowrite;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class EmployeeTest {
private ApplicationContext app;
@Before
public void bbefore(){
this.app = new ClassPathXmlApplicationContext("mao/shu/spring/autowrite/autowrite.xml");
}
@Test
public void testGet(){
Employee employee = (Employee) this.app.getBean("employee");
System.out.println(employee);
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/aa3de6a0c1f493bda5a19dfc05e44eea.png)
自动装配的缺点
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c94f0cc9e85b29850192dbcd8efa0015.png)