1. 程式人生 > >spring4.0.0之環境搭建

spring4.0.0之環境搭建

     dist包只是spring框架的核心jar包 還需下載其相應的依賴jar包 在上面的下載頁面  找到3.0.1.RELEASE  下載

  2.在javaee--eclipse環境下新建一個dynamic web project,名為spring_first  

進入到上一步下載解壓的spring-framework-4.0.0.M1的目錄中 進入libs資料夾  找到spring-context-support-4.0.0.M1.jar和spring-core-4.0.0.M1.jar和spring-beans-4.0.0.M1.jar三個jar包 將之拷貝到spring_first\WebContent\WEB-INF\lib目錄下

  同時 在上一步下載的依賴包中 即spring-framework-3.0.1.RELEASE-dependencies\org.apache.commons\com.springsource.org.apache.commons.logging\1.1.1\com.springsource.org.apache.commons.logging-1.1.1.jar  找到commons-logging的jar包 同樣新增到spring_first\WebContent\WEB-INF\lib目錄下

新增完以上四個jar包後 效果如下

   

3.編寫spring的配置檔案  可以參看spring官網提供的手冊  在spring-framework-4.0.0.M1\docs\spring-framework-reference\htmlsingle目錄中開啟index.html

點選上面的5.2.1 配置元資料  就會看到如下配置資訊

<?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">

  <bean id="..." class="...">
    <!-- collaborators and configuration for this bean go here -->
  </bean>

  <bean id="..." class="...">
    <!-- collaborators and configuration for this bean go here -->
  </bean>

  <!-- more bean definitions go here -->

</beans>

在spring_first的src目錄下新建一個first.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">

  <bean id="firstSpring" class="com.undergrowth.FirstSpring">
   
  </bean>

  

</beans>


4.編寫com.undergrowth.FirstSpring類

 FirstSpring.java

package com.undergrowth;

import java.util.Date;

public class FirstSpring {
	
	public void first()
	{
		System.out.println("第一個spring程式"+new Date().toLocaleString());
	}
}


5.編寫測試程式碼 在src目錄下新建一個junit test case

      

在Junit.java的檔案中加入測試程式碼 如下

package com.junit;

import static org.junit.Assert.*;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.undergrowth.FirstSpring;

public class Junit {

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	@Test
	public void test() {
		ApplicationContext ct=new ClassPathXmlApplicationContext("first.xml");
        FirstSpring sf=(FirstSpring) ct.getBean("firstSpring");
        sf.first();
	}

}


  執行test方法 結果報錯 如下

    

表示式解析類無法找到 去spring-framework-4.0.0.M1\libs中找到spring-expression-4.0.0.M1.jar 新增到lib中

再次執行 沒有錯誤了 打印出結果了

以上即是spring4.0.0的環境配置