package com.atChina.Test3;
public class Student {
private String name;
private int age;
private School school;
public Student(){
System.out.println("无参数构造方法...");
}
public Student(String myName, int myAge, School mySchool){
System.out.println("有参数构造方法...");
this.name = myName;
this.age = myAge;
this.school = mySchool;
}
public void setSchool(School school) {
this.school = school;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", school=" + school
+ "]";
}
}
package com.atChina.Test3;
public class School {
private String address;
private String name;
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "School [address=" + address + ", name=" + name + "]";
}
public void setName(String name) {
this.name = name;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!-- 引用Spring的多个Schema空间的格式定义文件 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
">
<!-- 构造注入: spring调用类的有参数构造方法,在构造方法中给属性赋值
语法: 使用<constructor-arg>表示构造方法的参数.
一个构造方法的参数对应一个<constructor-arg>标签
-->
<!-- 构造注入 -->
<bean id="student" class="com.atChina.Test3.Student">
<!-- 构造注入: 使用name属性
name:构造方法的形参名
value:简单类型参数的值
ref:引用类型参数的值
-->
<constructor-arg name="myName" value="林冲" />
<constructor-arg name="myAge" value="23" />
<constructor-arg name="mySchool" ref="xuexiao" />
</bean>
<!-- 构造注入, 使用index属性-->
<bean id="student2" class="com.atChina.Test3.Student">
<!-- 构造注入: 使用index属性
index:表示构造方法参数的位置,从0开始
value:简单类型参数的值
ref:引用类型参数的值
-->
<constructor-arg index="0" value="武松" />
<constructor-arg index="2" ref="xuexiao" />
<constructor-arg index="1" value="24" />
</bean>
<!-- 构造注入, 省略index属性, 参数顺序必须要与构造器参数顺序一致 -->
<bean id="student3" class="com.atChina.Test3.Student">
<!-- 构造注入: 使用index属性
index:表示构造方法参数的位置,从0开始
value:简单类型参数的值
ref:引用类型参数的值
-->
<constructor-arg value="鲁智深" />
<constructor-arg value="25" />
<constructor-arg ref="xuexiao" />
</bean>
<bean id="xuexiao" class="com.atChina.Test3.School">
<property name="name" value="武警大学"/>
<property name="address" value="阳谷县" />
</bean>
</beans>