Spring-IoC-DI-基于xml的依赖注入-使用set方法进行注入(案例十一:提取集合注入部分)

案例十一:提取集合注入部分

可以使用util名称空间创建集合类型用于其他bean外部引用来使用

1、先导入util名称空间

在这里插入图片描述

2、再在xsi中加入

http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
注意一定要加入否则报错
之后创建集合

(1)创建对象

package com.orz.spring.collection;

import java.util.List;

/**
 * @author orz
 * @create 2020-08-14 21:58
 */
public class Student {
    private String sname;
    private List<String> list;

    public void setSname(String sname) {
        this.sname = sname;
    }

    public void setList(List<String> list) {
        this.list = list;
    }
    public void show()
    {
        System.out.println(sname);
        System.out.println(list);
    }
}

(2)、配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/util
                           http://www.springframework.org/schema/util/spring-util.xsd">

    <!--  抽取集合  -->
    <util:list id="couserlist">
        <value>Java程序设计</value>
        <value>移动应用开发</value>
        <value>数据库</value>
    </util:list>


    <bean id="student" class="com.orz.spring.collection.Student">
        <property name="sname" value="李华"></property>
        <!--  注入集合属性      -->
        <property name="list" ref="couserlist"></property>
    </bean>


</beans>

(3)测试

package com.orz.spring.collection;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author orz
 * @create 2020-08-14 22:18
 */
public class Test1 {
    @Test
    public void test1()
    {
        ApplicationContext context=new ClassPathXmlApplicationContext("bean9.xml");
        Student student = context.getBean("student", Student.class);
        student.show();

    }
}

(4)、结果

李华
[Java程序设计, 移动应用开发, 数据库]

 

posted @ 2020-08-14 22:31  orz江小鱼  阅读(186)  评论(0编辑  收藏  举报