spring-注入list集合对象(值是对象)

    科技2025-05-01  10

    1.创建stu类

    public class Stu { // //1.数组类型 // private String[] courses; // // //2.list集合属性 // private List<String> list; // // //3.map集合类型 // private Map<String,String> map; // // //4.set集合属性类型 // private Set<String> set; private List<Course> courseList; public void setCourseList(List<Course> courseList) { this.courseList = courseList; } // public void setSet(Set<String> set) { // this.set = set; // } // // public void setMap(Map<String, String> map) { // this.map = map; // } // // public void setList(List<String> list) { // this.list = list; // } // // public void setCourses(String[] courses) { // this.courses = courses; // } // public void test(){ // System.out.println(Arrays.toString(courses)); // System.out.println(list); // System.out.println(map); // System.out.println(set); // } }

    2.创建Course类

    public class Course { private String cname; public void setCname(String cname) { this.cname = cname; } }

    3.配置bean1.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 name="stu" class="com.spring.collections.Stu"> <!--数组类型的注入--> <!-- <property name="courses">--> <!-- <array>--> <!-- <value>Struts框架</value>--> <!-- <value>Spring框架</value>--> <!-- </array>--> <!-- </property>--> <!-- &lt;!&ndash;list类型的注入&ndash;&gt;--> <!-- <property name="list">--> <!-- <list>--> <!-- <value>mybatis框架</value>--> <!-- <value>Spring MVC</value>--> <!-- </list>--> <!-- </property>--> <!-- &lt;!&ndash;map类型的注入&ndash;&gt;--> <!-- <property name="map">--> <!-- <map>--> <!-- <entry key="JAVA" value="java"></entry>--> <!-- <entry key="SSM" value="ssm"></entry>--> <!-- </map>--> <!-- </property>--> <!-- &lt;!&ndash;set类型注入&ndash;&gt;--> <!-- <property name="set">--> <!-- <set>--> <!-- <value>kevin</value>--> <!-- <value>Ron</value>--> <!-- </set>--> <!-- </property>--> <!--注入list集合类型,值是对象--> <property name="courseList"> <list> <ref bean="course1"></ref><!--ref注入course对象1--> <ref bean="course2"></ref> </list> </property> </bean> <!-- 创建多个course对象--> <bean id="course1" class="com.spring.collections.Course"> <property name="cname" value="Spring5"></property> </bean> <bean id="course2" class="com.spring.collections.Course"> <property name="cname" value="MyBatis"></property> </bean> </beans>
    Processed: 0.014, SQL: 8