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"));