文章目录
一、什么是自动装配(自动装配只针对对象类型)
二、自动装配的过程
1.引入依赖
2.创建两个类(User和School)
3.配置bean.xml
4.测试结果
一、什么是自动装配(自动装配只针对对象类型)
根据指定的装配规则(属性名称或者属性类型),Spring自动将匹配的属性值进行注入
二、自动装配的过程
1.引入依赖
org.springframework
spring-beans
5.2.5.RELEASE
org.springframework
spring-core
5.2.5.RELEASE
org.springframework
spring-context
5.2.5.RELEASE
junit
junit
4.13.1
test
2.创建两个类(User和School)
org.springframework spring-beans5.2.5.RELEASE org.springframework spring-core5.2.5.RELEASE org.springframework spring-context5.2.5.RELEASE junit junit4.13.1 test
2.创建两个类(User和School)
代码如下(示例):
public class User {
private String name;
private Integer age;
private School school;
public void add(){
System.out.println("user add 方法。。。。。");
}
public class School {
private User user;
public void add(){
System.out.println("school add 方法。。。。");
}
3.配置bean.xml
因为自动xml自动装配只适用于对象类型的自动装配,所以一般类型的属性值用之前的方式注入即可,否则将没有值
4.测试结果
@Test
public void test(){
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("bean.xml");
User user = context.getBean(User.class);
System.out.println(user.getName());
user.getSchool().add();
System.out.println("****************");
School school= context.getBean(School.class);
school.getUser().add();
}
如有不足或可以改进之处,还望指正,可以一起交流!



