1. 程式人生 > >eclipse中匯入spring詳細過程

eclipse中匯入spring詳細過程

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專案就完成了。