Java中有java.util.List、java.util.Set、java.util.Map等集合。
如果在Bean中需要给这些集合注入可以有一下几种注入方式。
public class SomeBean {
private String[] someStrArray;
private List someList;
private Map someMap;
....
}
<beans>
<bean id="someBean" class="com.baidu.SomeBean">
<property name="someArray"> <!--数组注入也是用list-->
<list>
<value>Hello!Justin!</value>
<value>Hello!Momor!</value>
<value>Hello!Bush!</value>
</list>
</property>
<property name="someList">
<list>
<value>Hello!Justin!</value>
<ref bean="someObj1"/>
<ref bean="someObj2"/>
</list>
</property>
<property name="someMap">
<map>
<entry key="somekey1">
<ref bean="someObj1"/>
</entry>
<entry key="somekey2">
<value>Hello!Justin!</value>
</entry>
</map>
</property>
</bean>
</beans>
Set集合注入方式
<set>
<value>a set element</value>
<ref bean="otherBean"/>
<ref bean="anotherBean"/>
</set>
Spring 中的 Propertites 是常用的属性
可以把学生信息封装到Properties props
如:
public class Student{
private Properties propertis;
public Properties getPropertis(){
return propertis;
}
public void setPropertis(Properties propertis){
this.propertis = propertis;
}
}
在applicationContext.xml中配置
<beans>
<bean id="stu" class="edu.hit.spring.demo05.Student">
<property name="propertis"> //表明要给当前对象设置属性值
<props>
<prop key="name">zhangsan</prop>
<prop key="age">23</prop>
<prop key="school">abcde</prop>
</props>
</property>
</beans>
</beans>
把这三条属性由一个Properties 对象进行管理。
如何取出来这对象的值?
在测试类中:
ApplicationContext app = new ClassPathApplicationContext("edu/hit/spring/demo06/applicationContext.xml");
Student stu = (Student)app.getBean("stu");
Properties pros = stu.getPropertis();
System.out.println(pros.getProperty("name")+"==="+pros.getProperty("age")+"==="+pros.getPropety("school"));