eclipse中导入spring详细过程

来源:互联网 发布:入门耳机 知乎 编辑:程序博客网 时间:2024/06/08 05:07

spring简介

Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson创建。简单来说,Spring是一个分层的JavaSE/EEfull-stack(一站式) 轻量级开源框架。

eclipse中导入spring

在导入spring之前先要下载spring-framework-x.xx.RELEASE下载地址:springframework 如果jdk版本在1.7或者以下的最好下载3.x.x.RELEASE的版本,我下载的为spring-framework-3.2.9.RELEASE的版本,下载完spring-framework-3.2.9.RELEASE之后,还要下载一个Commons Logging.zip文件下载地址commons-logging-1.2-src.zip,下载完这两个zip文件后,进行解压缩。打开eclipse新建一个Java project命名为springdemo,在springdemo上右键依次选择 build path–>configure build path–>Add Libarary–>User Libarary–>next–>user libararies –>New–>自定义一个名称比如说 spring_3.29,然后选中 spring_3.29,选择右边的Add JARS,将前面解压后spring-framework-3.2.9.RELEASE文件夹下的libs中的.jar文件全部选中然后ok就将spring框架导入到eclipse中了,同样将解压后commons-logging文件夹下的commons-logging-1.2.jar和commons-logging-1.2-javadoc.jar导入到eclipse中。
这里写图片描述
上面是导入后项目的图。

spring的简单使用

上面已经将spring框架导入到了我们当前的项目中,现在来一个小小的demo体验一下spring的用法。先看一下项目的框架:
这里写图片描述
在src文件夹下新建一个springTest类和一个PersonService类,

//PersonService 类public class PersonService {    private String name;    public void setName(String name) {        this.name = name;    }    public void info() {        System.out.println("此人名字为:"+name);          }}
//springTest 类package springdemo;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class SpringTest {    public static void main(String[] args) {        ApplicationContext ctx=new ClassPathXmlApplicationContext("bean.xml");        System.out.println(ctx);        PersonService p=ctx.getBean("PersonService", PersonService.class);        p.info();    }}

在src文件夹下新建一个bean.xml文件,一定要注意是在src文件夹下,不要将bean.xml的位置放错了不然程序运行会出现异常。

//bean.xml 文件<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"    "http://www.springframework.org/dtd/spring-beans.dtd"><beans><bean id="PersonService" class="springdemo.PersonService">   <property name="name" value="hanking">   </property></bean></beans>

到现在为止一切就绪,点击运行:

//输出org.springframework.context.support.ClassPathXmlApplicationContext@2635ee49: startup date [Tue May 16 15:32:21 CST 2017]; root of context hierarchy此人名字为:hanking

好了一个小小的spring项目就完成了。