1. 程式人生 > 實用技巧 >Eclipse建立簡單spring框架

Eclipse建立簡單spring框架

  Eclipse建立簡單spring框架

一:下載spring Framework

  https://repo.spring.io/release/org/springframework/spring/5.2.6.RELEASE/

  往下拉,選擇穩定且最新的版本,下載並解壓

二:匯入包:

  1. 四個包,前兩個十分重要,後面是描述功能的,分別在工程裡面匯入下面四個包,這也是ico基本包:

  1. 還需要匯入一個外包,也就是日誌包commons-logging-1.1.1.jar

  網站地址,請自行下載:https://www.jb51.net/softs/577391.html

  (可以把這幾個包方法哦Eclipse的JRE System包中,這樣更加方便)

三:Eclipse安裝Spring IDE外掛

  1)開啟Eclipse,點選Help->Install New Software

  2)選擇Add,新增Name(可以隨便取)和Location:http://dist.springsource.com/release/TOOLS/update/e4.10/

  3)勾選中下邊四個和Spring相關的檔案。Core/Spring IDE、Extensions/Spring IDE、Integrations/Spring IDE、Resources/Spring IDE四項

四:建立兩個class,一個就是最簡單的java程式碼,另外一個需要配置spring的容器和引入spring的配置檔案xml

  包1: ApplicationContext :

    ApplicationContext的中文意bai思是“應用前後關係”,它繼承自duBeanFactory介面,除了包含BeanFactory的所有功能之zhi外,在國際化dao支援、資源訪問(如URL和檔案)、事件傳播等方面進行了良好的支援,可應用在Java APP與Java Web中

五:例項:

  一:建立Dynamic web project

    注意在建立的過程中要把web.xml

  注意:這裡會出現類似這樣子的問題加上,至於怎麼加,請參考下面:https://blog.csdn.net/pseudonym_/article/details/77412812

  二:在Java Resources中的source加入下面兩個包,並建立之前說的實體類和測試類:

  並且按照上面圖片建立一個application.xml,好了,程式碼附上

Hello.java:

package com.spring_test;
​
public class Hello {
    public void sleep() {
        System.out.println("I want sleep");
    }
    
    public void study() {
        System.out.println("I want study");
    }
}

Test_hou_1.java:

package test;
​
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring_test.Hello;
​
public class Test_hou_1 {
    public static void main(String[] args) {
        //1.載入spring配置檔案
        ApplicationContext app=new ClassPathXmlApplicationContext("application.xml");
        //獲取配置物件,返回物件的需要強制轉換成Hello類的
        Hello hello=(Hello)app.getBean("hello");
        hello.sleep();
        hello.study();
    }
}

application.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--配置檔案的內容,id是在引用的名字,class是對應想要執行的類(這個必須要包含包路徑)  -->
<bean id="hello" class="com.spring_test.Hello"></bean>
 
</beans>

三:匯入jar包:

  右鍵專案->Build Path->Configure Build Path->點選Classpath->點選右側Add External JARs->匯入上面說的4個包,缺一個也不行哦

四:輸出:

六:出現問題:

Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path res

這個時候需要匯入aop包來解決問題,當然版本要與其他spring包的版本要一致