3 bean的两种传值方式

2019-02-27  本文已影响0人  陶然然_niit

如果一个JavaBean类,封装了一些属性,有简单的数据类型,有引用类型,如何在配置文件中给这个Bean的对象进行传值呢?

方法有两种:
1.通过属性传值
2.通过构造方法传值

注意:

Student和Phone的例子

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 +
                '}';
    }
}

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 +
                '}';
    }
}
    <!--配置一个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);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读