1、创建一个People类,设置其属性跟GetSet方法。
public class People {
private String name;//名字
private String age;//年龄
private char sex;//性别
private String iphone;//电话
private List<String> hoby;//爱好
private Map<String,String> address;//地址
private String[] friend;//朋友
private Properties pro; //集合类
@Override
public String toString() {
return "People [name=" + name + ", age=" + age + ", sex=" + sex
+ ", iphone=" + iphone + ", hoby=" + hoby + ", address="
+ address + ", friend=" + Arrays.toString(friend) + ", pro="
+ pro + "]";
}
public Properties getPro() {
return pro;
}
public void setPro(Properties pro) {
this.pro = pro;
}
public String[] getFriend() {
return friend;
}
public void setFriend(String[] friend) {
this.friend = friend;
}
public List<String> getHoby() {
return hoby;
}
public void setHoby(List<String> hoby) {
this.hoby = hoby;
}
public Map<String, String> getAddress() {
return address;
}
public void setAddress(Map<String, String> address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public String getIphone() {
return iphone;
}
public void setIphone(String iphone) {
this.iphone = iphone;
}
}
2、配置文件的配置(以bean.xml为例)
<bean id="people" class="cn.web.neusoft.entity.People">
<!--普通属性的注入 -->
<property name="name" value="李安"></property>
<property name="age" value="21"></property>
<property name="sex" value="男"></property>
<!--爱好List的依赖注入 -->
<property name="hoby">
<list>
<value>打游戏</value>
<value>听音乐</value>
<value>看电影</value>
</list>
</property>
<!--地址Map的依赖注入 -->
<property name="address">
<map>
<entry key="深圳" value="深圳大学"></entry>
<entry key="广州" value="华南理工大学"></entry>
<entry key="东莞" value="东莞理工学院"></entry>
</map>
</property>
<!--数组friend的依赖注入 -->
<property name="friend">
<list>
<value>小彭</value>
<value>小义</value>
<value>小春</value>
</list>
</property>
<!--对类Properties 属性集的依赖注入 -->
<property name="pro">
<props>
<prop key="pp1">pp1</prop>
<prop key="pp2">pp2</prop>
</props>
</property>
</bean>
</beans>
3、建立测试类
public class TestPeople {
public static void main(String[] args) {
/* ApplicationContext ac =new ClassPathXmlApplicationContext("bean.xml");*/
ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:bean.xml");
People p= (People) ac.getBean("people");
System.out.println(p.toString());
}
}
总结:构造方法注入,跟以上类似,不过需要在People类中添加所需的构造方法后,以三个参数为例,在配置文件中配置即可
<bean id="p" class="cn.web.neusoft.entity.People">
<constructor-arg index="0" value="小春子"></constructor-arg>
<constructor-arg index="1" value="11"></constructor-arg>
<constructor-arg index="2" value="男"></constructor-arg>
</bean>
不过值得注意的是,如果同时配置了构造方法和set方法注入,最终结果是set方法的值,前面的值被覆盖了。