Spring组合属性

来源:互联网 发布:csm算法 编辑:程序博客网 时间:2024/06/07 16:20

配置文件中可以使用如person.name形式配置属性,直接看代码
Person类:

public class Person {    private int id;    private String detail;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getDetail() {        return detail;    }    public void setDetail(String detail) {        this.detail = detail;    }}

ExampleBean类:

public class ExampleBean {    private Person person = new Person();    public Person getPerson() {        return person;    }    public void setPerson(Person person) {        this.person = person;    }}

配置文件:

    <bean id="item7x5Person" class="Item7x5.Person"/>    <bean id="item7x5ExampleBean" class="Item7x5.ExampleBean">        <property name="person.detail" value="浙江杭州"/>    </bean>

可以看到在配置文件中,使用<property name="person.detail" value="浙江杭州"/>注入。不过这样做的提前是person属性在ExampleBean中一开始就已经实例化,不然会引用空对象,抛出异常。 person.detail实际上先调用了getPerson()方法,然后在使用PersonsetDetail()方法。所以很容易理解为什么Person需要在ExampleBean中一开始就实例化。

<property name="person.a.b" value="xxx"/>就是表示example.getPerson().getA().setB(xxx);

0 0