<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<?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">
</beans>
// Student类
public class Student {
private String name;
private int age;
private School school;
public void setName(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 +
'}';
}
}
// School类
public class School {
private String name;
private String address;
public void setName(String name) {
this.name = name;
}
public void setAddress(String address) {
this.address = address;
}
}
<bean id="myStudent" class="club.soulhotel.Student">
<property name="age" value="21"/>
<property name="name" value="令狐冲"/>
<property name="school" ref="mySchool"/>
</bean>
<bean id="mySchool" class="club.soulhotel.School">
<property name="name" value="华山派"/>
<property name="address" value="华山"/>
</bean>
String config = "applicationContext.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(config);
Student myStudent = (Student) context.getBean("myStudent");
System.out.println(myStudent);
在使用set注入时,注意基本数据类型和引用数据类型如何注入。
set注入本质上是去调用javaBean类中我们写的set方法。