如果一个JavaBean类,封装了一些属性,有简单的数据类型,有引用类型,如何在配置文件中给这个Bean的对象进行传值呢?
方法有两种:
1.通过属性传值
2.通过构造方法传值
注意:
- 简单类型:用 name value
- 引用类型:用 name ref
Student和Phone的例子
- Phone类:封装品牌和价格属性,重载构造器、getter/setter,覆写toString()方法
package com.spring;
public class Phone {
private String brand;
private double price;
public Phone(String brand, double price) {
this.brand = brand;
this.price = price;
}
public Phone() {
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Phone{" +
"brand='" + brand + '\'' +
", price=" + price +
'}';
}
}
- Student类:封装姓名、年龄、手机属性,其中手机属性为引用类型,重载构造器、getter/setter,覆写toString()方法
package com.spring;
public class Student {
private String name;
private int age;
private Phone phone;
public Student(String name, int age, Phone phone) {
this.name = name;
this.age = age;
this.phone = phone;
}
public Student() {
}
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 Phone getPhone() {
return phone;
}
public void setPhone(Phone phone) {
this.phone = phone;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", phone=" + phone +
'}';
}
}
- beans.xml配置文件,配置Phone的bean和Student的bean,用到了属性传值和构造器传值,并根据类型不同采用vaule和ref不同的方式。
<!--配置一个Phone类的bean,并采用构造器传值-->
<bean id="phone" class="com.spring.Phone">
<constructor-arg name="brand" value="iPhoneX"/>
<constructor-arg name="price" value="6888.88"/>
</bean>
<!--配置一个Student类的bean,并采用属性传值,注意ref的使用-->
<bean id="student" class="com.spring.Student">
<property name="name" value="Tom"/>
<property name="age" value="21"/>
<property name="phone" ref="phone"/>
</bean>
- 编写主类进行测试
package com.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class StuentApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("/beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student);
}
}
-
运行结果,通过覆写toString(),打印对象,可以看到Student的对象中,引用了Phone的对象