前面已经介绍了如何给属性注入对象,下面介绍一下如何装配集合类型的属性
1.Set类型
private Set<String> sets=new HashSet<String>(); //我们需要给它添加set方法 public Set<String> getSets() { return sets; } public void setSets(Set<String> sets) { this.sets = sets; } public Set<String> showSet() { return sets; }
然后根据属性修改配置文件
<bean id="userService" class="com.szy.spring.service.UserServiceImpl"> <property name="sets"> <set> <value>Set1</value> <value>Set2</value> <value>Set3</value> </set> </property> </bean>
与以前不同的是我们在property下面添加了<set></set>
这样就能装配set类型的属性
2.List类型
List类型的属性和Set类型的方法一样,主要是把配置文件中的set修改成list。
private List<String> lists=new ArrayList<String>(); public List<String> getLists() { return lists; } public void setLists(List<String> lists) { this.lists = lists; } public List<String> showList() { return lists; }
配置文件修改如下
<bean id="userService" class="com.szy.spring.service.UserServiceImpl"> <property name="lists"> <list> <value>List1</value> <value>List2</value> <value>List3</value> </list> </property> </bean>
3.Properties类型
private Properties properties=new Properties(); public void setProperties(Properties properties) { this.properties = properties; } public Properties getProperties() { return properties; } public Properties showProperties() { return properties; }
配置文件需要如下配置
<bean id="userService" class="com.szy.spring.service.UserServiceImpl"> <property name="properties"> <props> <prop key="key1">Properties1</prop> <prop key="key2">Properties2</prop> <prop key="key3">Properties3</prop> </props> </property> </bean>
4.Map类型
private Map<String, String> maps=new HashMap<String, String>(); public List<String> getLists() { return lists; } public void setLists(List<String> lists) { this.lists = lists; } public Map<String, String> showMaps() { return maps; }
配置文件做相应的配置
<bean id="userService" class="com.szy.spring.service.UserServiceImpl"> <property name="maps"> <map> <entry key="key1" value="Map1"></entry> <entry key="key2" value="Map2"></entry> <entry key="key3" value="Map3"></entry> </map> </property> </bean>
这样就完成了对Map类型的属性进行装配。