set方法注入
在要注入属性的bean标签中进行配置。前提是该类有提供属性对应的set方法。
public class Student {
private String name;
private int id;
private int age;
private Dog dog;
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", id=" + id +
", age=" + age +
'}';
}
public Student() {
}
public Student(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
<bean class="com.leon.domain.Dog" id="dog">
<property name="name" value="小白"></property>
<property name="age" value="6"></property>
</bean>
<bean class="com.leon.domain.Student" id="student" >
<!--
name属性用来指定要设置哪个属性
value属性用来设置要设置的值
ref属性用来给引用类型的属性设置值,可以写上Spring容器中bean的id
-->
<property name="name" value="东南枝"></property>
<property name="age" value="20"></property>
<property name="id" value="1"></property>
<property name="dog" ref="dog"></property>
</bean>