5 配置Spring2.5
5.1 基礎配置
1) 導入spring包。下載spring-framework-2.5.6並解壓後,在spring-framework-2.5.6"dist目錄下找到spring.jar,引入到工程中。java
說明:spring.jar是包含有完整發布的單個jar包,spring.jar中包含除了 spring-mock.jar裏所包含的內容外其它全部jar包的內容,由於只有在開發環境下才會用到spring-mock.jar來進行輔助測試,正式應用系統中是用不得這些類的。除了spring.jar文件,Spring還包括有其它13個獨立的jar包,各自包含着對應的Spring組件,用戶能夠根據本身的須要來選擇組合本身的jar包,而沒必要引入整個spring.jar的全部類文件。這裏,爲了使用方便,咱們引入整個spring.jar。web
2) 配置web.xml文件。Jar包引入完成後,就開始配置spring了,首先修改web.xml文件,增長以下代碼:spring
<!--
* 從類路徑下加載spring的配置文件, 多個配置文件能夠用逗號和空格區分
* classpath: 關鍵字特指類路徑下加載-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:applicationContext*.xml
</param-value>
</context-param>
express
在這裏,咱們指定了spring配置文件的路徑,即WEB-INF/classes/spring目錄下的全部以applicationContext開頭命名的xml文件。session
3) 在src下面新建applicationContext.xml文件。首先給這個文件加上spring的標頭:app
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
</beans>
注意:標頭是2.5的 不要引入2.0, 錯了可能Spring就不能正確加載。 測試
5.2 示例
Spring基本配置完畢,讓咱們建個示例來測試一下吧,首先在test.spring包下建立兩個java文件:TUser.java、SpringTest.java。this
TUser.java:spa
1package test.spring;
2
3public class TUser implements java.io.Serializable {
4 private String username;
5 private String allname;
6 private String address;
7
8 public String getUsername() {
9 return this.username;
10 }
11 public void setUsername(String username) {
12 this.username = username;
13 }
14 public String getAllname() {
15 return this.allname;
16 }
17 public void setAllname(String allname) {
18 this.allname = allname;
19 }
20 public String getAddress() {