实体类Person:
public class Person {
private String name;
private List<Pet> pets;
private Map<String,Pet>petsMap;
//Properties类继承自Hashtable类并且实现了Map接口,也是使用一种键值对的形式来保存属性集。不过Properties有特殊的地方,就是它的键和值都是字符串类型。
private Properties pros;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Pet> getPets() {
return pets;
}
public void setPets(List<Pet> pets) {
this.pets = pets;
}
public Map<String, Pet> getPetsMap() {
return petsMap;
}
public void setPetsMap(Map<String, Pet> petsMap) {
this.petsMap = petsMap;
}
public Properties getPros() {
return pros;
}
public void setPros(Properties pros) {
this.pros = pros;
}
@Override
public String toString() {
return "Person [name=" + name + ", pets=" + pets + ", petsMap=" + petsMap + ", pros=" + pros + "]";
}
}
注入list:
<bean id="p1" class="com.igeek.lesson5.Person">
<property name="name" value="小田田"></property>
<property name="pets">
<list>
<ref bean="yw"/>
<ref bean="ms"/>
<!--注入空值-->
<null/>
<bean class="com.igeek.lesson4.Pet">
<property name="petName" value="白额吊睛大虫"></property>
<property name="age" value="40"></property>
</bean>
</list>
</property>
</bean>
<bean id="yw" class="com.igeek.lesson4.Pet">
<property name="petName" value="鹦鹉"></property>
<property name="age" value="20"></property>
</bean>
<bean id="ms" class="com.igeek.lesson4.Pet">
<property name="petName" value="蟒蛇"></property>
<property name="age" value="30"></property>
</bean>
若觉得代码量较多,也可以将list中的内容包起来
<bean id="p1" class="com.igeek.lesson5.Person">
<property name="name" value="田瑞瑞"></property>
<property name="pets">
<ref bean="pets"></ref>
</property>
</bean>
<util:list id="pets">
<ref bean="yw"/>
<ref bean="ms"/>
</util:list>
给MAP集合注入属性(两种形式):
<!--第一种-->
<bean id="p2" class="com.igeek.lesson5.Person">
<property name="name" value="李小花"></property>
<property name="petsMap">
<map>
<entry key="haha" value-ref="yw"></entry>
<entry key="hehe" value-ref="ms"></entry>
</map>
</property>
</bean>
<!--第二种-->
<bean id="p2" class="com.igeek.lesson5.Person">
<property name="name" value="李小花"></property>
<property name="petsMap">
<map>
<entry key="haha" value-ref="yw"></entry>
<entry key="hehe" value-ref="ms"></entry>
</map>
</property>
</bean>
网友评论