1.下载Spring的jar文件:
可按照如下方式下载:
登录http://repo.springsource.org/libs-release-local/站点,会出现一个目录列表,可沿着org->springframework->spring路径进入,可一看到Spring框架各版本的下载链接,选择下载其中一个压缩即可。
2.向项目中导入jar包,另还需导入commons-logging-1.1.3.jar包;log4j-api-2.3.jar与log4j-core-2.3.jar包是后面需要用到的处理错误的包,现在先导入,也可以不导入。如下为导入的jar包:
3.编写bean(实体类):
package com.study.beans; public class Users { private Integer id; private String name; private Integer age; public Users() { // TODO Auto-generated constructor stub } public Users(Integer id,String name,Integer age) { this.id = id; this.name = name; this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } 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; } @Override public String toString() { return "Users [id=" + id + ", name=" + name + ", age=" + age + "]"; } }
4.配置xml文件:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd"> <bean id="users" class="com.study.beans.Users"> <property name="id" value="1"/> <property name="name" value="zhangsan"/> <property name="age"> <value>20</value> </property> </bean> </beans>
5.在上面4个步骤做完之后,就可以测试框架是否搭建好了:这里写了一个Test类来测试:
package com.study.test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.io.ClassPathResource; import com.study.beans.Users; public class Test { public static void main(String[] args) { //根据配置文件创建ClassPathResource对象 ClassPathResource resource = new ClassPathResource("com/study/beans/bean.xml"); //创建BeanFactory DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); //创建读取xml的对象 XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory); //读取xml文件数据到factory中 reader.loadBeanDefinitions(resource); Users user = (Users)factory.getBean("users");//通过factory获取bean对象 System.out.println(user); } }