1. 项目结构
2.
Address.java
public class Address {
private String city;
private String street;
下面省略了getter 和setter....
}
Car.java
public class Car {
private String brand;
private double price;
private double tyrePerimeter;
下面省略了getter 和setter....
}
Person.java
public class Person {
private String name;
private int age;
private Car car;
//引用Address bean 的 city属性
private String city ;
//根据car 的price 确定info :car的price >=500000:豪车 ,否则为:普通车
private String info ;
下面省略了getter 和setter....
}
3. 测试:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpringSPEL {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans_spel.xml");
Address address = (Address) applicationContext.getBean("address");
System.out.println(address);
Car car = (Car) applicationContext.getBean("car");
System.out.println(car);
Person person = (Person) applicationContext.getBean("person");
System.out.println(person);
}
4. 运行结果:
Address [city=ShangHai, street=NanJingRoad]
Car [brand=BMW, price=1500000.0, tyrePerimeter=251.32741228718345]
Person [name=Tom, age=25, car=Car [brand=BMW, price=1500000.0, tyrePerimeter=251.32741228718345], city=ShangHai, info=豪车]