首先创建所需要的类:
package com.blushyes.vo;
public class Student {
private String name;
private Integer age;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
}
然后在resources文件夹下创建xml文件“beans.xml”,并添加Bean:
<bean id="myStudent" class="com.blushyes.vo.Student">
<property name="age" value="19" />
<property name="name" value="张三"/>
<property name="sex" value="男"/>
</bean>
从容器中提取对象:
String config = "beans.xml"; //指定config文件
ApplicationContext context = new ClassPathXmApplicationContext(config); //由config文件创建容器
Student student = (Student) context.getBean("myStudent"); //从容器中取得对象
System.out.println(student);
输出:
Student{name=‘张三’, age=19, sex=‘男’}