一. 导入jar包:
导入spring相关jar包
二. 创建spring的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
三. 创建实体类
package com.laishuai.bean;
public class Persion {
public String name;
public int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Persion{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
四. 创建对象
在spring的配置文件中添加如下代码于beans中:
//id为创建的实体名,class为要实例化的类
<bean id="laishuai" class="com.laishuai.bean.Persion">
//为实体添加属性值
//name为实体的属性名,必须和Persion的属性一致,value为该属性的值
<property name="name" value="LaiShuai"></property>
<property name="age" value="21"></property>
</bean>
五. 获取数据
public static void main(String[] args) {
//声明要应用的xml
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("BeanXml.xml");
//创建Persion的实体laishuai
Persion laishuai = (Persion) applicationContext.getBean("laishuai");
//打印一下赖帅
System.out.println(laishuai);
}
得出以下结果:
Persion{name='LaiShuai', age=21}
网友评论