4.Bean管理-外部注入对象属性.md

zhanglei 2022年05月30日 322次浏览

4.Bean管理-外部注入对象属性

Emp类

package Spring5.bean;

public class Emp {
    private String ename;
    private String gender;

    private Dept dept;

    public void setEname(String ename) {
        this.ename = ename;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Dept getDept() {
        return dept;
    }

    public void setDept(Dept dept) {
        this.dept=dept;
    }

    public void show(){
        System.out.println(ename+"::"+gender+"::"+dept);
    }
}

Dept类

package Spring5.bean;

public class Dept {
    private String dname;

    public void setDname(String dname) {
        this.dname = dname;
    }

    @Override
    public String toString() {
        return "Dept{" +
                "dname='" + dname + '\'' +
                '}';
    }
}

bean3.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
   
   <bean id="Emp" class="Spring5.bean.Emp">
        <property name="ename" value="张磊"></property>
        <property name="gender" value="男"></property>      
       <!--注入Dept的对象-->
        <property name="dept" ref="Dept"></property>
    </bean>
       <!--外部bean引用注入-->
    <bean id="Dept" class="Spring5.bean.Dept">
        <property name="dname" value="开发部"></property>
    </bean>
</beans>

测试结果

张磊::男::Dept{dname='开发部'}