Car.java
package com.gong.spring.beans; public class Car { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Car [name=" + name + "]"; } }
Student.java
package com.gong.spring.beans; public class Student { private String name; private int age; private double score; private Car car; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + ", score=" + score + ", car=" + car + "]"; } }
一、利用setter方法进行赋值
在bean中需要赋值的属性必须要有setter方法,同时bean中必须还要有一个无参的构造方法。如若不显示声明,则默认会有一个。
applicationContext.xml
<?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"> <bean id="car" class="com.gong.spring.beans.Car"></bean> <bean id="student" class="com.gong.spring.beans.Student"> <property name="name" value="tom"></property> <property name="age" value="12"></property> <property name="score" value="98.00"></property> <property name="car" ref="car"></property> <property name="car.name" value="baoma"></property> </bean> </beans>
关键就是标红的两个代码:先进行关联,然后进行级联赋值。
二、利用构造方法进行级联赋值
此时,要在Person中加一个有参构造方法:
public Student(String name, int age, double score, Car car) { super(); this.name = name; this.age = age; this.score = score; this.car = car; }
在Car中加一个无参构造方法:
public Car() { }
同时,对于这种方法,我们删除掉Person中name、age、score属性的getter和setter方法,保留car属性的getter和setter方法,程序仍然是可行的。
在applicationContext.xml中:
<?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"> <bean id="car" class="com.gong.spring.beans.Car"></bean> <bean id="student" class="com.gong.spring.beans.Student"> <constructor-arg value="tom"></constructor-arg> <constructor-arg value="12"></constructor-arg> <constructor-arg value="98.00"></constructor-arg> <constructor-arg ref="car"></constructor-arg> <property name="car.name" value="baoma"></property> </bean> </beans>
总结:
1.利用setter方法进行级联属性赋值需要:无参构造方法、setter方法。
2.利用构造器进行级联属性赋值需要:有参构造方法。
3.为级联属性赋值,属性先要初始化之后才可以为级联属性赋值,否则会有异常,即:
<property name="car" ref="car"></property>
<constructor-arg ref="car"></constructor-arg>
而在struct2中则不用,它会自动进行初始化。
原文地址:https://www.cnblogs.com/xiximayou/p/12150173.html
时间: 2024-10-07 11:01:19