两种方式:
①属性传值
②构造方法传值
name ref:引用类型
举例:Student类和Phone类
Ⅰ、Class Student 属性:封装name、age、phone 其中phone属于应用类型,所以之后的bean中使用ref,
自动生成constructor, getter/setter,覆写tostring()方法
如下:
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 int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
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 +
'}';
}
}
Ⅱ、Class Phone属性:封装brand、price 自动生成constructor, getter/setter,覆写tostring()方法
如下:
public class Phone {
private double price;
private double size;
public Phone(double price, double size) {
this.price = price;
this.size = size;
}
public Phone(){
}
public double getPrice() {
return price;
}
public double getSize() {
return size;
}
public void setPrice(double price) {
this.price = price;
}
public void setSize(double size) {
this.size = size;
}
@Override
public String toString() {
return "Phone{" +
"price=" + price +
", size=" + size +
'}';
}
}
Ⅲ、在beans.xml中对Phone类和Student类配置bean,分别用到属性传值和构造器传值
注意此处用到 ref
代码如下:
<!--属性传值-->
<bean id="phone" class="com.soft1721.spring.hello.Phone">
<property name="size" value="8.0"/>
<property name="price" value="10000"/>
</bean>
<!--构造器传值-->
<bean id="student" class="com.soft1721.spring.hello.Student">
<constructor-arg name="age" value="21"/>
<constructor-arg name="name" value="tom"/>
<constructor-arg name="phone" ref="phone"/>
</bean>
Ⅳ、编写主类进行测试
如下:
public class StudentApp {
public static void main(String[] args) {
ApplicationContext context=new
ClassPathXmlApplicationContext("beans.xml");
Student student=(Student) context.getBean("student");
System.out.println(student);
}
}
效果图:
效果图
网友评论