Bean 标签下的 <property> 元素中,使用以下元素配置 Java 集合类型的属性和参数,例如 List、Set、Map 以及 Properties 等
OtherType 类
public class OtherType { /*数组类型*/ private String[] arr; /*list集合类型*/ private List<String> list; /*map集合类型*/ private Map<String,String> map; /*set集合类型*/ private Set<String> set; public void setArr(String[] arr) { this.arr = arr; } public void setList(List<String> list) { this.list = list; } public void setMap(Map<String, String> map) { this.map = map; } public void setSet(Set<String> set) { this.set = set; } @Override public String toString() { return "OtherType{" + "arr=" + Arrays.toString(arr) + ", list=" + list + ", map=" + map + ", set=" + set + '}'; } }
spring.xml
<bean id="otherType" class="com.liu.c.OtherType"> <!--数组--> <property name="arr"> <array> <value>Java</value> <value>PHP</value> <value>C语言</value> </array> </property> <!--list--> <property name="list"> <list> <value>小张</value> <value>小刘</value> </list> </property> <!--map--> <property name="map"> <map> <entry key="Java" value="java"></entry> <entry key="PHP" value="php"></entry> </map> </property> <!--set--> <property name="set"> <set> <value>MySQL</value> <value>Redis</value> </set> </property> </bean>
Test测试
public class TestOtherType { public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); OtherType otherType = context.getBean("otherType", OtherType.class); System.out.println(otherType); } }
结果,成功注入
OtherType{ arr=[Java, PHP, C语言], list=[小张, 小刘], map={Java=java, PHP=php}, set=[MySQL, Redis]}
如果要注入的属性是对象类型的,使用 ref 即可