spring学习笔记(4)—— DI
在配置文件中配置类和类的依赖关系
学生类
package com.test.code;
public class Student {
private String name;
private String id;
private School school;
public void studentDoing(){
school.schoolDoing();
System.out.println("这是个学生类");
}
public School getSchool() {
return school;
}
public void setSchool(School school) {
this.school = school;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
学校类
package com.test.code;
public class School {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void schoolDoing(){
System.out.println("这是个学校类");
}
}
配置文件
语法
<bean id="名1" class="位置"/>
<bean id = "名2" class="位置">
<property name="类中属性名" ref="名1"/>
</bean>
名2类中有一属性是名1
名2类中有一属性是名1
property中name配置哪一个具体属性
property中ref属性参照的是哪一个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 http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="school" class="com.test.code.School"/>
<bean id = "student" class="com.test.code.Student">
<property name="school" ref="school"/>
</bean>
</beans>