1. 程式人生 > >spring 級聯屬性

spring 級聯屬性

1.People類

package com.hxzy;


public class People {


private String name;
private int age;
private Car car;

//必須有無參構造方法
public People() {

}

public People(String name, int age, Car car) {
super();
this.name = name;
this.age = age;
this.car = car;
}


public void setName(String name) {
this.name = name;
}

public void setAge(int age) {
this.age = age;
}


public void setCar(Car car) {
this.car = car;
}

//此處如果getCar方法缺少,會導致如下錯誤:

/*

Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'car.speed' of bean class [com.hxzy.People]: Nested property in path 'car.speed' does not exist; nested exception is org.springframework.beans.NotReadablePropertyException: Invalid property 'car' of bean class [com.hxzy.People]: Bean property 'car' is not readable or has an invalid getter method:

Does the return type of the getter match the parameter type of the setter?

*/
public Car getCar() {
return car;
}

@Override
public String toString() {
return "People [name=" + name + ", age=" + age + ", car=" + car + "]";
}

}

2.Car類

package com.hxzy;


public class Car {


private String brand;
private String corp;
private double price;
private int speed;




public Car(String brand, String corp, double price) {
super();
this.brand = brand;
this.corp = corp;
this.price = price;
}

//此處如果不寫,執行時報錯
public void setSpeed(int speed) {
this.speed = speed;
}


@Override
public String toString() {
return "Car [brand=" + brand + ", corp=" + corp + ", price=" + price
+ ", speed=" + speed + "]";
}


}

3.配置檔案

<?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="people" class="com.hxzy.People">
        <property name="name" value="王強強"></property>
        <property name="age" value="15"></property>
    </bean>
    -->
    
    <bean id="car" class="com.hxzy.Car">
        <constructor-arg value="audi" ></constructor-arg>
        <constructor-arg value="shanghai" ></constructor-arg>
        <constructor-arg value="300000" ></constructor-arg>
    </bean>
    
    <bean id="people2" class="com.hxzy.People">
        <constructor-arg value="私人"></constructor-arg>
        <constructor-arg value="25"></constructor-arg>
<constructor-arg ref="car"></constructor-arg>    
<property name="car.speed" value="300"></property>    
     </bean>

</beans>

4.

package com.hxzy;


import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class Test {


public static void main(String[] args) {
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("config.xml");
//People man = new People();

People man = (People) ctx.getBean("people2");
System.out.println(man);

}
}