基於XML的依賴注入
1.設值注入:底層呼叫屬性setter方法進行賦值,一定要有setter方法。使用property.
2.構造注入:一定要有帶引數的構造方法。使用constructor-arg.
通過設值注入原始碼為:
1.School類:
public class School {
private String sname;
public void setSname(String sname) { this.sname = sname; } @Override public String toString() { return "School [sname=" + sname + "]"; }
}
2.Student類及setter方法
public class Student {
private String name; //成員變數
private int age;
private School school; //自定義類物件
public void setXxx(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public void setSchool(School school) { this.school = school; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + ", school=" + school + "]"; }
}
3.XML配置檔案
<?xml version="1.0" encoding="UTF-8"?><bean id="mySchool" class="com.abc.di01.School"> <property name="sname" value="清華大學"/> </bean> <bean id="student" class="com.abc.di01.Student"> <property name="xxx" value="張三"/> <property name="age" value="21"/> <property name="school" ref="mySchool"/> </bean>
4.測試類MyTest
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
//設值注入
public class MyTest {
@Test
public void tests01(){
//建立Spring容器物件,載入Spring的配置檔案(在類路徑下)
String config = "com/abc/di01/applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(config);
Student student = (Student) ac.getBean("student");
System.out.println(student);
}
}
測試結果為:
Student [name=張三, age=21, school=School [sname=清華大學]]
通過構造注入原始碼為:
1.School類:
public class School {
private String sname;
public void setSname(String sname) {
this.sname = sname;
}
@Override
public String toString() {
return "School [sname=" + sname + "]";
}
}
2.Student類及有參構造方法
public class Student {
private String name; //成員變數
private int age;
private School school; //自定義類物件
public Student(String name, int age, School school) {
super();
this.name = name;
this.age = age;
this.school = school;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", school=" + school + "]";
}
}
3.XML配置檔案
<?xml version="1.0" encoding="UTF-8"?><bean id="mySchool" class="com.abc.di02.School">
<property name="sname" value="清華大學"/>
</bean>
<bean id="student" class="com.abc.di02.Student">
<constructor-arg name="name" value="李四"/>
<constructor-arg name="age" value="22"/>
<constructor-arg name="school" ref="mySchool"/>
</bean>
4.測試類MyTest
Student [name=李四, age=22, school=School [sname=清華大學]]