如果一個(gè)JavaBean類(lèi),封裝了一些屬性,有簡(jiǎn)單的數(shù)據(jù)類(lèi)型,有引用類(lèi)型,如何在配置文件中給這個(gè)Bean的對(duì)象進(jìn)行傳值呢?
方法有兩種:
1.通過(guò)屬性傳值
2.通過(guò)構(gòu)造方法傳值
注意:
- 簡(jiǎn)單類(lèi)型:用 name value
- 引用類(lèi)型:用 name ref
Student和Phone的例子
- Phone類(lèi):封裝品牌和價(jià)格屬性,重載構(gòu)造器、getter/setter,覆寫(xiě)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類(lèi):封裝姓名、年齡、手機(jī)屬性,其中手機(jī)屬性為引用類(lèi)型,重載構(gòu)造器、getter/setter,覆寫(xiě)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,用到了屬性傳值和構(gòu)造器傳值,并根據(jù)類(lèi)型不同采用vaule和ref不同的方式。
<!--配置一個(gè)Phone類(lèi)的bean,并采用構(gòu)造器傳值-->
<bean id="phone" class="com.spring.Phone">
<constructor-arg name="brand" value="iPhoneX"/>
<constructor-arg name="price" value="6888.88"/>
</bean>
<!--配置一個(gè)Student類(lèi)的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>
- 編寫(xiě)主類(lèi)進(jìn)行測(cè)試
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);
}
}
-
運(yùn)行結(jié)果,通過(guò)覆寫(xiě)toString(),打印對(duì)象,可以看到Student的對(duì)象中,引用了Phone的對(duì)象
運(yùn)行結(jié)果
