Student类:
public class Student {
private String name;//学生姓名
private Integer age; //学生年龄
private Car car;//学生的汽车
@Override
//重写toString()方法方便进行测试
public String toString() {
return "Student [name=" + name + ", age=" + age + ", car=" + car + "]";
}
//构造函数
public Student(String name, Integer age, Car car) {
System.out.println("我是带参构造");
this.name = name;
this.age = age;
this.car = car;
} public Student() {
System.out.println("我是无参构造");
}
//属性访问器
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
} }
Car类:
public class Car {
//汽车颜色
private String color;
//属性访问器
public String getColor() {
return color;
} public void setColor(String color) {
this.color = color;
}
//重写toString()方法方便测试
@Override
public String toString() {
return "Car [color=" + color + "]";
} }
applicationContext.xml配置:
<bean id="car" class="cn.wz.entity.Car">
<property name="color" value="白色"/>
</bean> <bean id="stu" class="cn.wz.entity.Student">
<!--通过constructor-arg元素向构造方法传入参数-->
<constructor-arg index="0" value="王哲"/>
<constructor-arg index="1" value="18"/>
<constructor-arg index="2" ref="car"/>
</bean>
测试代码:
public class Test {
public static void main(String[] args) { hasArgumentConstructor();
}
public static void hasArgumentConstructor(){
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = context.getBean("stu",Student.class);
System.out.println(student); }
}
最终运行结果:
使用p命名空间实现属性注入
<bean id="car" class="cn.wz.entity.Car">
<property name="color" value="白色"/>
</bean>
<bean id="stu" class="cn.wz.entity.Student" p:name="王哲" p:age="18" p:car-ref="car" />