spring基于Xml管理bean---Ioc依赖注入:map类型的属性

文章目录

    • map类型属性


map类型属性

创建学生类、教师类,学生和教师具有多对一的关系

学生类

package com.guigu.map;

import java.util.Map;

public class Studey {


    //学生
    private  String  sid;

    private  String  name;


    //学生对应老师(一对多关系)


//    map  根据k获取v值
    private Map<String,Teacher> map;

    public void setMap(Map<String, Teacher> map) {
        this.map = map;
    }

    public void setSid(String sid) {
        this.sid = sid;
    }

    public void setName(String name) {
        this.name = name;
    }



    public  void  studey(){

        System.out.println("学生id = " + sid+"学生姓名"+name);

        System.out.println("map = " + map);

    }
}

教师类

package com.guigu.map;

public class Teacher {

    //教师

    private  String teacherId;

    private  String teacherName;


    public void setTeacherId(String teacherId) {
        this.teacherId = teacherId;
    }

    public void setTeacherName(String teacherName) {
        this.teacherName = teacherName;
    }


    @Override
    public String toString() {
        return "Teacher{" +
                "teacherId='" + teacherId + '\'' +
                ", teacherName='" + teacherName + '\'' +
                '}';
    }
}

bean.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">


    <!--
    1.创建bean对象
    2.注入普通类型的属性

    3.Studey中注入map类型属性

    -->


    <!--创建Studey对象-->
    <bean id="studey" class="com.guigu.map.Studey">
        <!--注入普通类型进行赋值-->
        <property name="sid" value="0001"></property>
        <property name="name" value="tom"></property>


       //
        <property name="map">
            <map>
                <entry>

                    <key>

                        <value>10000</value>

                    </key>
                    <!--ref:引入对象-->
                    <ref bean="teacher"></ref>

                </entry>


            </map>

        </property>
    </bean>

    <!--创建Teacher对象-->
    <bean id="teacher" class="com.guigu.map.Teacher">
        <!--注入普通类型进行赋值-->
        <property name="teacherId" value="01"></property>
        <property name="teacherName" value="小明老师"></property>

    </bean>
    <bean id="teacher1" class="com.guigu.map.Teacher">
        <!--注入普通类型进行赋值-->
        <property name="teacherId" value="01"></property>
        <property name="teacherName" value="小明老师"></property>

    </bean>


</beans>

你可能感兴趣的:(spring,spring,xml,java)