Spring框架中提取list集合类型属性注入

提取list集合类型属性注入

前言

对于某一个类型属性通用性较高的情况下,可以单独的提取出来,给需要的bean进行引用。

有关类的创建见《Spring框架中集合属性为对象的注入方法》

引入名称空间

首先,需要在xml配置文件头中,添加名称空间util,直接拿原始内容进行更改即可,操作如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
		xmlns:util="http://www.springframework.org/schema/util"
	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
						http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

多出来的为util相关内容:

<beans xmlns:util="http://www.springframework.org/schema/util"
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd>

就是将之前的beans所包含的内容粘贴复制并改为util即可。

编写xml配置文件

使用util名称空间,来对需要注入的参数进行抽取。

<!-- 提取List集合类型属性注入 -->
<bean id="stud" class="com.action.spring.collectiontype.Stud">
    <property name="lists" ref="booklist"></property>
	<property name="courseList" ref="studlist"></property>
</bean>

<util:list id="booklist">
    <value>JAVA开发</value>
    <value>Spring学习</value>
    <value>MyBatise学习</value>
</util:list> 

<util:list id="studlist">
    <bean id="course1" class="com.action.spring.collectiontype.Course">
        <property name="cname" value="Spring5学习"></property>
    </bean>
    <bean id="course2" class="com.action.spring.collectiontype.Course">
        <property name="cname" value="MyBatise学习"></property>
    </bean>
    <bean id="course3" class="com.action.spring.collectiontype.Course">
        <property name="cname" value="JAVA学习"></property>
    </bean>
</util:list>

运行结果

有关类的创建见《Spring框架中集合属性为对象的注入方法》
里面详细了描述了相关测试类的建立方式和源码。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/jerrygaoling/article/details/108832698