使用Spring框架的步骤

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包:

 使用Spring框架的步骤_第1张图片

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文件:



 
	
	
		
		
		
			20
		
	

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);
		
	}
}





你可能感兴趣的:(JavaEE,Spring框架,使用步骤)