要進行基於Spring的功能開發,就需要添加Spring的開發支援環境。所謂的Spring支援環境,就是在Java Web應用中添加Spring所需要的JAR、TLD、XML檔案,有了這些檔案我們就可以開發Spring相關的功能代碼了。
本文有兩個內容:
1.Spring環境構建
2.Spring使用----測試範例
1.Spring環境構建
構建步驟如下:
對著項目工程右鍵選擇myeclipse-----Add Spring Capabilities
A
可以對相應的類庫進行選擇
以及路徑的配置
在配置完成後,單擊"完成"按鈕即可完成Spring支援環境的添加。
2.Spring使用----測試範例
2.1 在applicationContext.xml中添加Bean配置
首先在applicationContext.xml中添加如程式2.1所示的Bean配置元素。
程式2.1 applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"><bean id="HelloWorld" class="Test.HelloWorld"><property name="message"><value>World</value></property></bean>
這裡我們配置了一個ID為"HelloWorld"的Bean對象,所使用的類為Test.HelloWorld,並且為該類的屬性"message"設定了一個注入的值"World"。這是<bean>元素的一種最常用的配置形式。
2.2 建立Bean類--HelloWorld.java
下面建立Bean類Test.HelloWorld.java。根據以上XML檔案配置,該類需要包含一個屬性message,因此添加一個String類型的變數message,並添加getter/setter的函數,然後添加一個測試函數execute()用以輸出被注入的參數變數message,如程式2.2所示。
程式2.2 HelloWorld.java
package Test;public class HelloWorld { protected String message; public String getMessage() {return message;} public void setMessage(String message) {this.message = message;} public void execute() {System.out.println("Hello " + getMessage() + "!");}}
2.3 運行測試類別Test.java
然後,編寫測試類別Test.java。使用FileSystemXmlApplicationContext來讀取XML設定檔applicationContext,即會返回ApplicationContext類型的變數ctx。然後使用ctx的getBean()函數取得配置的Bean對象"HelloWorld",該名稱是XML檔案中配置的Bean名稱。取得的對象經過強制類型轉換變為HelloWorld類型,將其命名為hello,並調用hello的execute()執行輸出。實現的完整代碼如程式2.3所示。
程式2.3 測試類別Test.java
package Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.FileSystemXmlApplicationContext;public class springTest {public static void main(String[] args) {ApplicationContext ctx = new FileSystemXmlApplicationContext("src/applicationContext.xml");HelloWorld hello = (HelloWorld) ctx.getBean("HelloWorld");hello.execute();}}
運行該程式,如果輸出"Hello World"則表示環境已經支援Spring了。
如果出現"java.io.FileNotFoundException: WebRoot/WEB-INF/applicationContext.xml"異常,則說明applicationContext.xml資源檔放置的路徑不對,該路徑需要是相對於當前項目demo的路徑。