如何在春天中赋值级联属性

  介绍

这篇文章将为大家详细讲解有关如何在春天中赋值级联属性,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

汽车。java

package  com.gong.spring.beans;      public  class  Car  {   private 才能;String 名称;      public 才能;String  getName (), {   ,,,return 名称;   ,,}      public 才能;void  setName (String 名称),{   ,,,this.name =,名称;   ,,}      @Override才能   public 才能;String  toString (), {   ,,,return “Car  [name=? +, name  +,“]”;   ,,}   ,,   }

学生。java

package  com.gong.spring.beans;      public  class  Student  {   private 才能;String 名称;   private 才能;int 年龄;   private 才能;double 分数;   private 才能;Car 汽车;   public 才能;String  getName (), {   ,,,return 名称;   ,,}   public 才能;void  setName (String 名称),{   ,,,this.name =,名称;   ,,}   public 才能;int  getAge (), {   ,,,return 年龄;   ,,}   public 才能;void  setAge (int 年龄),{   ,,,this.age =,年龄;   ,,}   public 才能;double  getScore (), {   ,,,return 分数;   ,,}   public 才能;void  setScore (double 分数),{   ,,,this.score =,分数;   ,,}   public 才能;Car  getCar (), {   ,,,return 汽车;   ,,}   public 才能;void  setCar (Car 车),{   ,,,this.car =,汽车;   ,,}   @Override才能   public 才能;String  toString (), {   ,,,return “Student  [name=? +, name  +,,,,岁=?+,age  +,,,,分数=?+,score  +,,,,车=?+,car  +,“]”;   ,,}   ,,   ,,   }

<强>一、利用setter方法进行赋值

在bean中需要赋值的属性必须要有setter方法,同时bean中必须还要有一个无参的构造方法。如若不显示声明,则默认会有一个。

applicationContext。xml

& lt; ? xml  version=?.0“,编码=癠TF-8" ?比;   http://www.springframework.org/schema/beans" & lt; beans  xmlns=?;   ,,xmlns: xsi=癶ttp://www.w3.org/2001/XMLSchema-instance"   ,,xsi: schemaLocation=? http://www.springframework.org/schema/beans , http://www.springframework.org/schema/beans/spring-beans.xsd"比;   ,,   & lt;才能bean  id=癱ar",类=癱om.gong.spring.beans.Car"祝辞& lt;/bean>   ,,   & lt;才能bean  id=皊tudent",类=癱om.gong.spring.beans.Student"比;   ,,,& lt; property  name=皀ame",值=https://www.yisu.com/zixun/疤滥贰?   <属性名="年龄" value=" 12 ">   <属性名="分数" value=" 98.00 ">   <属性名="车" ref="车">   <属性名=" car.name " value="宝马">            

关键就是标红的两个代码:先进行关联,然后进行级联赋值。

<强>二,利用构造方法进行级联赋值

此时,要在人中加一个有参构造方法:

public 学生(名称、String  int 年龄,,double 分数,,Car 车),{   ,,,超级();   ,,,this.name =,名称;   ,,,this.age =,年龄;   ,,,this.score =,分数;   ,,,this.car =,汽车;   以前,,}

在车中加一个无参构造方法:

public 汽车(),{   }

同时,对于这种方法,我们删除掉人中姓名、年龄、分数属性的getter和setter方法,保留车属性的getter和setter方法,程序仍然是可行的。

在applicationContext。xml中:

& lt; ? xml  version=?.0“,编码=癠TF-8" ?比;   http://www.springframework.org/schema/beans" & lt; beans  xmlns=?;   ,,xmlns: xsi=癶ttp://www.w3.org/2001/XMLSchema-instance"   ,,xsi: schemaLocation=? http://www.springframework.org/schema/beans , http://www.springframework.org/schema/beans/spring-beans.xsd"比;   ,,   & lt;才能bean  id=癱ar",类=癱om.gong.spring.beans.Car"祝辞& lt;/bean>   ,,   & lt;才能bean  id=皊tudent",类=癱om.gong.spring.beans.Student"比;   ,,,& lt; constructor-arg 价值=https://www.yisu.com/zixun/"汤姆">      

如何在春天中赋值级联属性